首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >iOS | 动态获取字符串宽高并添加约束

iOS | 动态获取字符串宽高并添加约束

作者头像
CnPeng
发布于 2021-02-03 15:13:43
发布于 2021-02-03 15:13:43
1.2K0
举报
文章被收录于专栏:CnPengDevCnPengDev

在 iOS 实际编码过程中,我们可能会需要通过代码动态的向某个 View 视图中添加 UILabel, 此时,我们必须手动的为这些 UILabel 对象添加约束条件,否则,这些 UILabel 将会因为没有约束条件而无法显示。

只有获取到 UILabel 中填充的字符串所占据的宽高信息信息之后,才能为其添加具体的约束,所以——

通过代码获取字符串所占视图宽度:

代码语言:javascript
复制
/*
* 获取字符串边框
*/
func getStrBoundRect(str:String,font:UIFont,constrainedSize:CGSize,
                         option:NSStringDrawingOptions=NSStringDrawingOptions.usesLineFragmentOrigin)->CGRect{
    let attr = [NSAttributedString.Key.font:font]
    let rect=str.boundingRect(with: constrainedSize, options: option, attributes:attr , context: nil)
    return rect
}

当我们获取到字符串所占视图区域 Rect 之后,就可以动态添加约束了,示例如下:

代码语言:javascript
复制
/*
* 添加约束
*/
func addLabelConstraint(targetView:UIView,preRightBound:CGFloat,viewWidth:CGFloat)->CGFloat{
    let totalPadding=CGFloat(6)
    let childSpace=CGFloat(5)
    
    targetView.translatesAutoresizingMaskIntoConstraints=false
    
    let leftBound = CGFloat(preRightBound==0 ? 0:(preRightBound+childSpace))
    targetView.leftAnchor.constraint(equalTo: self.spendCouponView.leftAnchor, constant: leftBound).isActive=true
    let rightBound = leftBound+viewWidth+totalPadding
    targetView.rightAnchor.constraint(equalTo: self.spendCouponView.leftAnchor, constant: rightBound).isActive=true
    targetView.topAnchor.constraint(equalTo: self.spendCouponView.topAnchor, constant: 0).isActive=true
    targetView.bottomAnchor.constraint(equalTo: self.spendCouponView.bottomAnchor, constant: 0).isActive=true
    
    return rightBound
}

上述两个函数的调用示例如下:

代码语言:javascript
复制
 //添加满减券子视图
 func addSpendCouponChildView(){
     
     var preRightBound=CGFloat(0)
     
     for i in 0 ..< 4{
         let spendCouponChildView=UILabel()
         spendCouponChildView.text="20减18-\(i)"
         spendCouponChildView.font=UIFont.n8
         spendCouponChildView.textColor=UIColor.emphasizeText
         spendCouponChildView.layer.borderColor=UIColor.emphasizeText.cgColor
         spendCouponChildView.layer.borderWidth=0.5
         spendCouponChildView.layer.cornerRadius=2
         spendCouponChildView.textAlignment  = .center
         self.spendCouponView.addSubview(spendCouponChildView)

         let rect=getStrBoundRect(str: spendCouponChildView.text ?? "",font: spendCouponChildView.font, constrainedSize: CGSize(width: spendCouponView.width,height:15 ))

         preRightBound = addLabelConstraint(targetView: spendCouponChildView, preRightBound: preRightBound, viewWidth: rect.width)
     }
 }

最终效果如下:

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-01-29,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档