gpt4 book ai didi

ios - 具有固定宽度和 NSAttributedString 的 UILabel 的渲染行数

转载 作者:可可西里 更新时间:2023-11-01 05:33:57 24 4
gpt4 key购买 nike

我有一个 UILabel,其文本是通过 -setAttributedText: 动态设置的NSAttributedString 包含各种动态属性,即到处都是不同字符范围的不同字体或样式。 UILabel 的宽度是受限的(通过自动布局),高度是可变的 (numberOfLines=0)。

我需要确定的是在给定 NSAttributedString 和宽度约束的情况下呈现的文本行数。

请注意,我不是在寻找标签的高度,而是在寻找渲染的行数。另请注意,我无法基于 font.lineHeight 执行任何计算,因为字体在整个 NSAttributedString 中各不相同。

对于某些背景,想要做的是为具有 1 行的标签设置 label.textAlignment=NSTextAlignmentCenter,为具有 2 行的标签设置 label.textAlignment=NSTextAlignmentLeft或更多行。例如,在自动布局和 UILabel 完成其业务后,我会在 -[UIViewController viewDidLayoutSubviews] 中执行此操作。或者也许有更简单的方法来实现相同的目标。

最佳答案

这是 Swift 3 版本

extension NSAttributedString {

func numberOfLines(with width: CGFloat) -> Int {

let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT)))
let frameSetterRef : CTFramesetter = CTFramesetterCreateWithAttributedString(self as CFAttributedString)
let frameRef: CTFrame = CTFramesetterCreateFrame(frameSetterRef, CFRangeMake(0, 0), path.cgPath, nil)

let linesNS: NSArray = CTFrameGetLines(frameRef)

guard let lines = linesNS as? [CTLine] else { return 0 }
return lines.count
}
}

希望对你有帮助

关于ios - 具有固定宽度和 NSAttributedString 的 UILabel 的渲染行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27683559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com