Swift检查TextView是否为空

9
我想知道如何正确检查一个UITextView是否为空。
目前我有一个验证函数来进行检查:
if let descText = myTextView.text {
    if descText.isEmpty {
        descErrorLabel.isHidden = false
    } else {
        descErrorLabel.isHidden = true
    }
}

这样是否足以防止用户发送空的文本视图,或者我还需要检查空格,例如:

stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty

后者更好。 - Bista
http://stackoverflow.com/questions/33036458/how-to-check-uitextfield-is-not-blank-in-swift-2-0-is-there-better-way-to-count/33036724 - Bhavin Bhadani
我个人建议检查空格和换行符,但用户可以发送“ ”吗?这是允许的吗?这有意义吗?两种方法都是有效的,但哪种更好取决于规范。 - Larme
1个回答

16
您可以把它全部整合成类似这样的东西...
func validate(textView textView: UITextView) -> Bool {
    guard let text = textView.text,
        !text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else {
        // this will be reached if the text is nil (unlikely)
        // or if the text only contains white spaces
        // or no text at all
        return false
    }

    return true
}

然后您可以验证任何UITextView,例如...

if validate(textView: textView) {
    // do something
} else {
    // do something else
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接