如何检查 NSMutableAttributedString 字体大小是否比某个值 smaller/greater?
How to check if an NSMutableAttributedString font size is smaller/greater than some value?
我尝试通过检查 NSMutableAttributedString 字体大小是否比某个值 smaller/greater 来创建一个 if 块。我找不到关于这个的解释。代码示例如下:
if textView.font.pointSize < 30 {
//execute
}
textView 中的字符串是 NSMutableAttributedString
。有什么想法吗?
未测试,但应该可以解决问题
extension UITextView {
func maxPointSize() -> CGFloat {
var max: CGFloat = font?.pointSize ?? 0.0 //In case you mix .attributedText and .text but I'd recommand to avoid mixing them.
guard let attributedString = attributedText else { return max }
attributedString.enumerateAttribute(.font, in: NSRange(location: 0, length: attributedString.length), options: []) { value, range, pointee in
guard let font = value as? UIFont else { return }
max = font.pointSize > max ? font.pointSize : max
}
return max
}
}
思路是枚举NSAttributedString
里面的字体,取最大值
然后
if textView.maxPointSize() < 30 {
//execute
}
我尝试通过检查 NSMutableAttributedString 字体大小是否比某个值 smaller/greater 来创建一个 if 块。我找不到关于这个的解释。代码示例如下:
if textView.font.pointSize < 30 {
//execute
}
textView 中的字符串是 NSMutableAttributedString
。有什么想法吗?
未测试,但应该可以解决问题
extension UITextView {
func maxPointSize() -> CGFloat {
var max: CGFloat = font?.pointSize ?? 0.0 //In case you mix .attributedText and .text but I'd recommand to avoid mixing them.
guard let attributedString = attributedText else { return max }
attributedString.enumerateAttribute(.font, in: NSRange(location: 0, length: attributedString.length), options: []) { value, range, pointee in
guard let font = value as? UIFont else { return }
max = font.pointSize > max ? font.pointSize : max
}
return max
}
}
思路是枚举NSAttributedString
里面的字体,取最大值
然后
if textView.maxPointSize() < 30 {
//execute
}