【问题标题】:How to check if an NSMutableAttributedString font size is smaller/greater than some value?如何检查 NSMutableAttributedString 字体大小是否小于/大于某个值?
【发布时间】:2021-03-24 10:19:58
【问题描述】:

我尝试通过检查 NSMutableAttributedString 字体大小是否小于/大于某个值来创建 if 块。我找不到关于这个的解释。代码示例如下:

if textView.font.pointSize < 30 {
   //execute
}

textView 中的字符串是NSMutableAttributedString。有什么想法吗?

【问题讨论】:

  • 在一个 NSAttributedString 中你可以有多个尺寸。所以如果你想检查大小,你需要枚举(就像你之前的问题一样来改变它)。不要像以前那样改变它,只需保持大小,并获得最大的一个或类似的东西?
  • @Larme 谢谢Larme,我没想到。然后我尝试不同的方法。你真是个乐于助人的程序员,我真的很感激

标签: swift font-size nsmutableattributedstring


【解决方案1】:

未经测试,但应该可以解决问题

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    相关资源
    最近更新 更多