代码之家  ›  专栏  ›  技术社区  ›  Sidney Liu

Xcode 9中的Swift 4-如何在NSAttribute字符串中使用boundingrect?

  •  3
  • Sidney Liu  · 技术社区  · 7 年前

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

    但最后我在打印中得到了错误的宽度,那么为什么以及如何得到正确的宽度呢。

    1 回复  |  直到 7 年前
        1
  •  7
  •   tereks    7 年前

    使用

    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。宽度(高度:高度) 哪里 高度(>);0