Swift - check if attributed text is empty
Asked Answered
N

2

7

I have a UITextField on which I set a current value as attributed text as follows:

public var currentValue: NSAttributedString {
    get {
        return inputField.attributedText ?? NSAttributedString()
    }
    set {
        inputField.attributedText = newValue
    }
}

This was previously just a String but I now need to add formatting to parts of the text.

However, I have a method I need to pass on these fields which begins with the condition to see if the field is empty. Previously I started this with:

if textField.currentValue.isEmpty {
  // Perform logic
}

However, obviously NSAttributedText has no isEmpty member. How can I perform the same check on NSAttributedText?

Nitroparaffin answered 14/9, 2020 at 21:52 Comment(0)
H
12

NSAttributedText has no isEmpty property but it has one called length. You can simply check if it is equal to zero:

if currentValue.length == .zero {
  // Perform logic
} 

Another option is to simply check if your text field hasText

if textField.hasText {

} else {

}
Haldan answered 15/9, 2020 at 5:45 Comment(0)
E
4

There's also attributedText.string.isEmpty

Electronic answered 30/11, 2021 at 16:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.