解决Swift中boundingRect偶尔计算宽度不准

2022-07-11  本文已影响0人  萤火驻守心间

初始化属性相同的UILabel

private func setUpLabel() -> UILabel {
        let label = UILabel()
        label.textColor = .white
        label.text = "骨髓增生异常综合征-难治性贫血伴原始细胞(MDS-RAEB)"
        label.font = .systemFont(ofSize: 14)
        label.textAlignment = .center
        label.backgroundColor = .lightGray
        return label
    }

根据文本内容计算label的宽度
方式一:

extension String {
    //获取文字的宽高
    func getStringSize(font: UIFont, viewSize: CGSize) -> CGSize {
        let rect = self.boundingRect(with: viewSize, options: [.usesLineFragmentOrigin,.truncatesLastVisibleLine,.usesFontLeading,.usesDeviceMetrics], attributes: [NSAttributedString.Key.font: font], context: nil)
        return rect.size
    }
}

方式二:

func getWidthWithLabel(_ curtitle: String?, _ curfont: UIFont) -> CGFloat {
        let temlabel = UILabel(frame: CGRect(x: 0, y: 0, width: 1000, height: 0))
        temlabel.text = curtitle
        temlabel.font = curfont
        temlabel.sizeToFit()
        let temwidth = temlabel.frame.size.width
        return ceil(temwidth)
    }

显示结果:

override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = .white
        
        let label1 = setUpLabel()
        let label2 = setUpLabel()
        view.addSubview(label1)
        view.addSubview(label2)
        //第一种计算方式
        let strSize = label1.text?.getStringSize(font: label1.font, viewSize: CGSize(width: UIScreen.main.bounds.size.width-12*4, height: CGFloat(MAXFLOAT)))
        if let labelw = strSize?.width {
            label1.frame =  CGRect(x: 0.5*(UIScreen.main.bounds.size.width-labelw), y: 100, width: labelw, height: 30)
        }
        
        //第二种计算方式
        let strw = getWidthWithLabel(label2.text, label2.font)
        label2.frame =  CGRect(x: 0.5*(UIScreen.main.bounds.size.width-strw), y: 150, width: strw, height: 30)
    }
image.png
上一篇下一篇

猜你喜欢

热点阅读