[iOS]Label-获取字符串的宽度(Swift)

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

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

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

/*
* 获取字符串边框
*/
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 之后,就可以动态添加约束了,示例如下:

/*
* 添加约束
*/
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
}

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

 //添加满减券子视图
 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)
     }
 }

效果如下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CnPeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值