检查 OSX 中的 NSTextView 是否为空

Check if the NSTextView is empty in OSX

如果 NSTextView 为空(用户未在 textView 中输入任何内容),我将尝试显示消息,但找不到合适的内置 method.In NSTextFiled 案例,这很简单。

if(countElements(emailTextField.stringValue) == 0)

mac

中是否有 NSTextView 的替代品

获得对NSTextView持有的NSTextStorage对象的访问权限,并使用(只读)length属性统计存储对象的元素基础 string 属性:

// Mark: NSTextViewDelegate implementation

func textDidChange(notification: NSNotification) {

    if let textView = notification.object as? NSTextView {
        if let storage = textView.textStorage {
            if storage.length == 0 {
                // text-view is empty
            }
        }
    }
}

如果您查看 NSTextStorage class 参考,您会发现它实际上只是一个 NSAttributedString 子 class。 NSAttributedString 有一个 string 属性 和一个 length 属性 - 这是我们用来的 length 属性确定字符串是否为 'empty'.