用户不应该能够删除文本字段中的给定符号

User should not be able to delete given symbol in textfield which is a text

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

我必须限制用户从 swift 的文本字段中删除此符号。用户可以在不删除此符号的情况下从文本字段中删除任何内容。

由于最可能的情况是欧元符号将始终出现在文本字段中并且是第一个字符,我会检查要更改的字符范围是否长于 0 并从 0 开始。(这将无论第一个位置的符号如何工作)

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if range.length>0  && range.location == 0 {
            return false
    }
    return true
}

但是,如果欧元符号并不总是在文本字段中,您可以通过获取对用户正在更改的字符串的引用并检查它是否包含欧元符号来检查用户是否正在删除此符号:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if range.length>0  && range.location == 0 {
        let changedText = NSString(string: textField.text!).substringWithRange(range)
        if changedText.containsString("€") {
            return false
        }
    }
    return true
}