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

克洛克斯

我想获取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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

UnrecognizedSelector 如何在 Xcode9/Swift4 中成为可能?

可选类型“日期?”的值 未解开;你的意思是使用“!” 或者 '?'?在 Swift 4 XCode 9 中

MFMailComposeViewController,Swift 4,Xcode 9

setValuesForKeys在Xcode 9中的Swift 4中不起作用

我是否需要在Xcode 9,Swift 4中使用cocoapods明确声明要安装哪个版本的alamofire

使用未声明的类型'Date'Xcode 9 Swift 4

Xcode 9 / Swift 4 AVCaptureMetadataOutput setMetadataObjectTypes使用availableMetadataObjectTypes

使用 Swift 4 和 Xcode 9 获取 JSON 数据

使用Swift 4 App(Xcode 9.X)在iOS 11中缺少第一响应者吗?

如何在Swift 3中使用Pods使用Swift 4.0构建xcode 9项目?

Xcode 9卡在Swift 4迁移上

更新到Xcode 9和Swift 4

Swift4-Xcode 9 PCH错误

如何在Xcode 4中设置NSZombieEnabled?

xcode swift4 如何更改 viewdidload 中的页面

Xcode 9 中的 Swift 4 - 读取核心数据中的数据失败

Swift 4-Xcode 9 Beta 4-NSKernAttributeName与NSAttributedStringKey

如何设置透明的导航栏?iOS 11 Swift 4 Xcode 9

如何从数字键盘上调用textFieldShouldReturn Xcode 9 Swift 4

如何删除XCode9“有向Swift 4的转换可用”警告?

使用Swift 4 / Xcode 9从CLPLacemark获取完整的地址字符串

使用“新构建系统(预览版)”新功能时出现的问题Xcode 9 Swift 4

使用Xcode 9和Swift 4本地化应用程序的最佳方法是?

Xcode 9无法使用Pod构建Swift 4项目

使用Swift和xCode9 beta4创建静态库

在Swift 4 Xcode 9 Beta 6中无法对UIButton进行编程,无法添加目标

闭包元组不支持Xcode 9 Swift 4中的解构

XCode 9 Swift 4中没有这样的模块'FBAudienceNetwork'

在Swift 4 Xcode 9中比较Int数组切片元素时出错