Xcode 9中的Swift 4 - 如何在NSAttributedstring中使用boundingrect?

问题描述 投票:2回答:1

我想获取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)!)

但最后我在打印中得到了假宽度,所以为什么以及如何获得正确的宽度。

ios swift swift4 nsattributedstring
1个回答
2
投票

使用

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)
    }
}

然后得到width = attr.width(height:height),其中height> 0

© www.soinside.com 2019 - 2024. All rights reserved.