【发布时间】:2019-06-08 14:43:31
【问题描述】:
有没有办法将NSAttributedString 对象的NSParagraphStyle / NSMutableParagraphStyle 属性的lineSpacing 属性设置为字体基本/原始lineSpacing 的百分比?
lineSpacing 是NSParagraphStyle 而不是UIFont 的属性,因此无法知道字体的原始lineSpacing 是什么。
作为参考,这是我为将lineSpacing 分配给UILabel 编写的一个小扩展(累积,不会导致标签的属性字符串上的信息丢失):
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 标签,这样可以很容易地搜索到,但我的名声不允许我这样做)
【问题讨论】:
标签: ios uikit foundation core-text uifont