swift2 如何在Swift中限制UITextField中的某些字符?

nzrxty8p  于 2022-11-06  发布在  Swift
关注(0)|答案(8)|浏览(279)

我正在创建一个在启动时要求输入用户名的小应用程序。我想让它不可能使用#$@!^&等字符(也包括“空格”)。我看了一下这篇文章here,但它完全是用Objective-C写的。提前感谢。

nwlqm0z1

nwlqm0z11#

Swift 4 iOS 11.2.x基于使用扩展名,在本例中测试字符串是否为有效的十六进制数。

extension String {

var containsValidCharacter: Bool {
    guard self != "" else { return true }
    let hexSet = CharacterSet(charactersIn: "1234567890ABCDEFabcdef")
    let newSet = CharacterSet(charactersIn: self)
    return hexSet.isSuperset(of: newSet)
  }
}

它的用法与UITextFieldDelegate类似。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return (string.containsValidCharacter)
}

虽然我在以前的文章中读到过CharacterSets不支持由多个Unicode组成的字符。所以我想要小心使用。

7y4bm7vi

7y4bm7vi2#

既然你明确地要求斯威夫特,我已经翻译了链接问题中的第一个问题。

let notAllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.";

func textField(
    textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String)
    -> Bool
{
    let set = NSCharacterSet(charactersInString: notAllowedCharacters);
    let inverted = set.invertedSet;

    let filtered = string
        .componentsSeparatedByCharactersInSet(inverted)
        .joinWithSeparator("");
    return filtered != string;

}
vc6uscn9

vc6uscn93#

internal func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
     if let text = string{
           if text == "#" || text == "$" || text == "!"{ \\and so on
              return false
           }
     }
     return true
}
gajydyqb

gajydyqb4#

雨燕2.3

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        let characters = ["#", "$", "!", "&","@"]
        for character in characters{
            if string == character{
                print("This characters are not allowed")
                return false
            }
        }
}
mzsu5hc0

mzsu5hc05#

因此,这可能是限制空格的最可靠方法。使用此用户将无法粘贴/键入****空格
这是您使用Swift 3实施的方式。
将下面提到的extension片段添加到Swift文件中;

extension String {

var containsWhitespace: Bool {
    for scalar in unicodeScalars {
        switch scalar.value {
        case 0x20:
            return true
        default:
            continue
        }
    }
    return false
  }
}

在您的ViewController Swift文件中,从情节提要中拖出您的Editing Changed示例和UITextFieldReferencing Outlet,如下图所示:

按如下所述使用拖动的示例:
将插座引用为:

@IBOutlet weak var textField: UITextField!

和编辑更改为:

@IBAction func textChanged(_ sender: UITextField) {
    if (textField.text!.containsWhitespace) == true {
        print("Restrict/Delete Whitespace")
        emailField.deleteBackward()
    } else {
        print("If Its not Whitespace, Its allowed.")
    }
}

这将在用户尝试键入/粘贴空格时检测并删除空格。

xu3bshqb

xu3bshqb6#

Swift 4 iOS 11.2.x基于使用扩展名,在本例中测试字符串是否为有效的十六进制数。
扩展字符串{

var containsValidCharacter: Bool {
    guard self != "" else { return true }
    let hexSet = CharacterSet(charactersIn: "1234567890ABCDEFabcdef")
    let newSet = CharacterSet(charactersIn: self)
    return hexSet.isSuperset(of: newSet)
  }
}

它的用法与UITextFieldDelegate类似。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return (string.containsValidCharacter)
}
g0czyy6m

g0czyy6m7#

Swift:3和一个不同的方法:
为viewDidLoad中的文本字段更改添加目标函数:

override func viewDidLoad() {
    super.viewDidLoad()
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(textField:)), for: UIControlEvents.editingChanged)
 }

在目标函数中,简单地检测输入的字符并将其替换为空白。2我已经测试过了,它可以防止用户在文本字段中输入任何不需要的字符。

func textFieldDidChange(textField: UITextField) {

    if let textInField = textField.text{
        if let lastChar = textInField.characters.last{

            //here include more characters which you don't want user to put in the text field
            if(lastChar == "*")
            {

                textField.text  = textInField.substring(to: textInField.index(before: textInField.endIndex))

            }
        }
    }

}
wpx232ag

wpx232ag8#

添加@Evdzhan Mustafa所说的内容。您需要添加一个return语句,以防字符串为空。如果没有它,您将无法删除文本。修改代码如下:
Swift 3版本

let notAllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.";

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string.isEmpty{
        return true
    }

    print("String: \(string)")
    let set = NSCharacterSet(charactersIn: notAllowedCharacters);
    let inverted = set.inverted;

    let filtered = string.components(separatedBy: inverted).joined(separator: "")
    print("String Filtered: \(filtered)")
    return filtered != string;
}

相关问题