SWIFT:Nstextfield 只允许指定字符 [英] SWIFT: Nstextfield allow only specified characters

查看:118
本文介绍了SWIFT:Nstextfield 只允许指定字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有人告诉我如何快速允许 nstexfield 中的特定字符.例如,当用户尝试输入不在列表中的字符时,nstexfield 不会在字段中显示该字符.非常简单.有很多 IOS 示例,但找不到 OSX 示例.

I need somebody to show me how to allow specific characters in a nstexfield in swift. For example when a user tries to enter a character which is not in the list the nstexfield will not show that character in the field.. Very simple. There are many IOS examples out there but could not find an OSX example.

推荐答案

首先添加一个 NSTextFieldDelegate 到你的类...然后

First add a NSTextFieldDelegate to your class... and then

添加:

 override func controlTextDidChange(obj: NSNotification) {
    let characterSet: NSCharacterSet = NSCharacterSet(charactersInString: " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789-_").invertedSet
    self.textField.stringValue = (self.textField.stringValue.componentsSeparatedByCharactersInSet(characterSet) as NSArray).componentsJoinedByString("")
}

您必须将 self.textfield 替换为您自己想要控制的文本字段.

you have to replace self.textfield with your own textfield which you want to control.

SWIFT 4 编辑

 override func controlTextDidChange(_ obj: Notification) {
    let characterSet: NSCharacterSet = NSCharacterSet(charactersIn: " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789-_").inverted as NSCharacterSet
    self.textField.stringValue =  (self.textField.stringValue.components(separatedBy: characterSet as CharacterSet) as NSArray).componentsJoined(by: "")
}

这篇关于SWIFT:Nstextfield 只允许指定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆