Swift - 检查属性文本是否为空

问题描述 投票:0回答:2

我有一个 UITextField,我将当前值设置为属性文本,如下所示:

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

这以前只是一个字符串,但现在我需要为部分文本添加格式。

但是,我有一个需要传递这些字段的方法,该方法以条件开头来查看该字段是否为空。之前我是这样开始的:

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

但是,显然 NSAttributedText 没有 isEmpty 成员。如何对 NSAttributedText 执行相同的检查?

swift string nsattributedstring nsmutableattributedstring
2个回答
13
投票

NSAttributedText
没有
isEmpty
属性,但有一个名为
length
的属性。您可以简单地检查它是否等于零:

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

另一种选择是简单地检查您的文本字段是否

hasText

if textField.hasText {

} else {

}

5
投票

还有

attributedText.string.isEmpty

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.