ios - 快速检查 textview 是否为空

标签 ios swift

我想知道如何正确检查 uitextview 是否为空。

现在我有一个验证功能可以进行检查:

if let descText = myTextView.text {
    if descText.isEmpty {
        descErrorLabel.isHidden = false
    } else {
        descErrorLabel.isHidden = true
    }
}

这足以防止用户发送空 TextView ,或者我还必须检查空格,例如:

stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty

最佳答案

你可以把它全部卷成这样......

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
}

关于ios - 快速检查 textview 是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40021280/

相关文章:

ios - 我需要 UIView 上的 UITableView 帮助( Storyboard项目)

ios - 带有 Objective-C 选择器 'dealloc()' 的方法 'dealloc' 与带有相同 Objective-C 选择器的隐式析构器冲突

ios - 在 VIPER 项目中启用 lightContent 状态栏样式

swift - 如何使用 RevenueCat 在没有 Internet 连接的情况下验证自动续订订阅

ios - 依赖分析错误,XCode 4.6

ios - tabBar 减小嵌套 ViewController 中 View 的大小

swift - UISearchBar 不适用于数组中的子部分

ios - 在 Objective-C 项目中导入 Swift 框架 - 错误 - 未知类型名称

swift - 如何在swift中设置嵌套?

ios - 在框架中覆盖 Storyboard中的图像