简体   繁体   English

可可-当NSTextfield中达到最大长度时,如何使textfield不允许输入文本?

[英]COCOA - How to make textfield doesn't allow text entry when max length is reached in NSTextfield?

I am newbie to MAC development. 我是MAC开发的新手。 If answer is already explained anywhere, please add link in comments. 如果答案已经在任何地方说明,请在评论中添加链接。 I will remove the question in that case. 在这种情况下,我将删除问题。

Currently, if textfield length reaches maximum count I'm showing an alert.But, still the last entered character is present in textfield so user needs a backspace. 当前,如果文本字段的长度达到最大数量,我会显示警报。但是,文本字段中仍然存在最后输入的字符,因此用户需要一个退格键。

I also tried using NSFormatter, but failed. 我也尝试使用NSFormatter,但失败了。

//CODE //码

override func controlTextDidChange(_ obj: Notification) {
  if let textField = obj.object as? NSTextField {
     if textField.stringValue.count > x {
         // display alert
     }
  }
}

What I am expecting is that user should enter text, but text should not be displayed. 我期望的是用户应该输入文本,但不应显示文本。 Instead of an alert, text entry shouldn't be allowed like we achieve in web. 像警报一样,不应该像我们在网络中那样实现文本输入。

Thanks in advance. 提前致谢。

At its simplest, all you need is to subclass Formatter and override 3 methods: 最简单的是,您需要Formatter子类并重写3个方法:

class MyFormatter: Formatter {
    var maxLength = Int.max

    override func string(for obj: Any?) -> String? {
        return obj as? String
    }

    override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
        obj?.pointee = string as NSString
        return true
    }

    override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>?, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
        return partialString.count <= maxLength
    }
}

Then set the formatter for your textfield: 然后为您的文本字段设置格式化程序:

let formatter = MyFormatter()
formatter.maxLength = 10

textField.formatter = formatter

This is enough to guard against users typing in more than 10 characters or paste in strings that are long than 10 characters. 这足以防止用户输入超过10个字符或粘贴长度超过10个字符的字符串。 If you want more advanced features like taking the first 10 characters when pasting in a long string, you should override isPartialStringValid(_:proposedSelectedRange:originalString:originalSelectedRange:errorDescription:) . 如果要使用更高级的功能,例如在粘贴长字符串时采用前10个字符,则应重写isPartialStringValid(_:proposedSelectedRange:originalString:originalSelectedRange:errorDescription:)

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

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