是否有方法将lineSpacing对象的NSParagraphStyle / NSMutableParagraphStyle属性的属性设置为字体基本/原始lineSpacing的百分比?
lineSpacing是NSParagraphStyle而不是UIFont的属性,因此不可能知道字体的原始lineSpacing是什么。
作为参考,下面是我为将lineSpacing分配给UILabel而编写的一个小小的扩展(累积的,不会导致标签的attributedString上的信息丢失):
import UIKit
extension UILabel {
/// -important: must be called after setting the `text` property so the computed NSRange would be valid
func setLineSpacing(with lineSpacing: CGFloat) {
// get safe string
guard let textString = self.text, !textString.isEmpty
else { return }
// get the range
let entireRange: NSRange = (textString as NSString).range(of: textString)
guard entireRange.isValidNSRange(within: textString)
else { assertionFailure() ; return }
// NSMutableAttributedText
guard let mutableAttributedText: NSMutableAttributedString = self.attributedText?.mutableCopy() as? NSMutableAttributedString
else { assertionFailure() ; return }
// NSParagraphStyle
var paragraphStyle: NSParagraphStyle? = mutableAttributedText.attribute(NSParagraphStyleAttributeName, at: 0, longestEffectiveRange: nil, in: entireRange) as? NSParagraphStyle
if paragraphStyle == nil {
// why TTTAttributedLabel :(
paragraphStyle = NSParagraphStyle()
}
// safe NSParagraphStyle
guard let safeParagraphStyle: NSParagraphStyle = paragraphStyle
else { assertionFailure() ; return }
// NSMutableParagraphStyle
guard let mutableParagraphStyle: NSMutableParagraphStyle = safeParagraphStyle.mutableCopy() as? NSMutableParagraphStyle
else { assertionFailure() ; return }
// this is where the magic happens
mutableParagraphStyle.lineSpacing = lineSpacing
mutableAttributedText.addAttribute(NSParagraphStyleAttributeName, value: mutableParagraphStyle, range: entireRange)
// assign attributed text which has all the existing attributes plus the new line spacing attribute which is inside the paragraphstyle attribute...
self.attributedText = mutableAttributedText
}
}
extension NSRange {
// Is it safe to use range on the string?
func isValidNSRange(within string: String) -> Bool {
if self.location != NSNotFound
&& self.length > 0
&& self.location + self.length - 1 < string.length
&& self.location >= 0
{
return true
} else {
return false
}
}
}我已经研究过这个问题了,在Stackoverflow上没有找到答案。所以我要分享我自己的FWIW。(我想加入CoreText标签,这样就可以很容易地搜索到,但我的名声不允许我)
https://stackoverflow.com/questions/54184432
复制相似问题