6

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?

DevB1
  • 1,235
  • 3
  • 17
  • 43

2 Answers2

11

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 {

}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
3

There's also attributedText.string.isEmpty

CoolPineapple
  • 275
  • 1
  • 3
  • 11