Search code examples
swiftfont-sizensmutableattributedstring

How to check if an NSMutableAttributedString font size is smaller/greater than some value?


I try to make an if block by checking if an NSMutableAttributedString font size is smaller/greater than some value. I couldn't find an explanation about this. Code sample is as follows:

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

where string inside textView is NSMutableAttributedString. Any ideas?


Solution

  • Not tested, but that should do the trick

    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
        }
    }
    
    

    The idea is to enumerate the fonts inside the NSAttributedString, and keep the max value.

    Then

    if textView.maxPointSize() < 30 {
       //execute
    }