我想使用NSMutableAttributedString
计算boundingRectWithSize
的尺寸。
当为所有范围添加所有属性时,它返回准确的值。
但是,当我添加部分范围属性(例如,部分颜色)时,它会返回不准确的值。
这是一个例子。
//: Playground - noun: a place where people can play
import UIKit
func makeSample(text text: String) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: text)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5.0
attributedString.addAttributes([
NSFontAttributeName: UIFont(name: "HiraKakuProN-W3", size: 14.0)!,
NSParagraphStyleAttributeName: paragraphStyle
], range: NSRange(location: 0, length: attributedString.length))
return attributedString
}
func height(of attributedString: NSMutableAttributedString) -> CGFloat {
let options = unsafeBitCast(
NSStringDrawingOptions.UsesLineFragmentOrigin.rawValue |
NSStringDrawingOptions.TruncatesLastVisibleLine.rawValue,
NSStringDrawingOptions.self)
return attributedString.boundingRectWithSize(CGSize(width: 100, height: CGFloat.max), options: options, context: nil).height
}
// one color string
let oneColorAttributedString = makeSample(text: "hello")
oneColorAttributedString.addAttribute(
NSForegroundColorAttributeName,
value: UIColor.blueColor(),
range: NSRange(location: 0, length: oneColorAttributedString.length) // whole range
)
print(height(of: oneColorAttributedString)) // print 14.0 <- OK
// partial color string
let partialColorAttributedString = makeSample(text: "hello")
partialColorAttributedString.addAttribute(
NSForegroundColorAttributeName,
value: UIColor.blueColor(),
range: NSRange(location: 0, length: 1) // first letter only
)
print(height(of: partialColorAttributedString)) // print 19.0 <- wrong value!!
我该如何避免这种情况? 这些配置是否不正确?