我想获取UILabel中某些文本的长度,并动态更改UILabel的width属性。
但是我不知道如何在函数boundingrect中设置参数。这是Apple Developer的文档。
func boundingRect(with size: CGSize,
options: NSStringDrawingOptions = [],
context: NSStringDrawingContext?) -> CGRect
,我尝试过这样
let attr = NSMutableAttributedString(string: "test test test test , this is test text. test test test test , this is test text. test test test test , this is test text. ")
//attr.addattributes
print(attr.boundingrect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 0), option: .truncatesLastVisibleLine
,context: nil)!)
但是最后我得到了错误的印刷宽度,所以为什么以及如何获得正确的宽度。
使用
public extension NSAttributedString {
public func width(height: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect,
options: [.usesLineFragmentOrigin, .usesFontLeading],
context: nil)
return ceil(boundingBox.height)
}
}
然后让let width = attr.width(height:height),其中height> 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句