如何检查 TextView 是否为空?

How to check if TextView is empty?

我已经使用这段代码来检查 Textview 是否为空。如果我给出 space,它工作正常,但如果我按下 "Enter" 按钮,它允许我在数据库中输入我的数据。这有什么问题吗?

func validation()->Int
{
    var i = 1

    //1st way

    if txt_view.text.isEmpty
    {
        var alert = UIAlertView()
        alert.title = "Message"
        alert.message = "Write Career Objective"
        alert.addButtonWithTitle("OK")
        alert.show()
        i = 0
    }

    //2nd way

    if txt_view.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == ""
    {
        var alert = UIAlertView()
        alert.title = "Message"
        alert.message = "Write Career Objective"
        alert.addButtonWithTitle("OK")
        alert.show()
        i = 0
    }

    return i
}

更改您的第二次尝试以包含新行:

if txt_view.text.stringByTrimmingCharactersInSet(
  NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
{
    var alert = UIAlertView()
    alert.title = "Message" 
    alert.message = "Write Career Objective"
    alert.addButtonWithTitle("OK")
    alert.show()
    i = 0
}

此外,与空字符串 == "" 相比,我总是更喜欢 isEmpty