简体   繁体   English

如何检测 UITextView 中的文本为空?

[英]How to detect text in UITextView is empty?

It is easy for UITextField to check empty text...But I have a custom UITextView.If I have input text like @" "; UITextField 检查空文本很容易......但是我有一个自定义的 UITextView。如果我输入了像 @" "; 这样的文本。 We don't know what I input,but only can read the length of the text.我们不知道我输入了什么,但只能读取文本的长度。 How can I detect the empty text like "\\n" , "", " "?Any idea?如何检测像 "\\n" 、 ""、" " 这样的空文本?知道吗?

You can check it:你可以检查一下:

if(![[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
   //string is all whitespace or newline

}

使用- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set和空白字符集并检查结果字符串的长度。

For Swift 5.1对于 Swift 5.1

    if textView.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
        // TextView is empty (or only has whitespaces and newlines) then ...
        // buttonSend.isEnabled = false
    } else {
        // TextView has some text, then ...
        // buttonSend.isEnabled = true
    }

You can check through counting characters if there will no character in uitextview then characters count will be 0 and we can check on it's base:如果 uitextview 中没有字符,您可以检查字符数,然后字符数将为 0,我们可以检查它的基础:

if(yourTextView.text.characters.count == 0)
    {
        //if empty then
    }
    else
    {
       //if not empty then
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM