Search code examples
swiftcharactertextfieldrestrict

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


enter image description here

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

I have to restrict user to delete this symbol from textfield in swift. User can delete any thing from textfield without deleting this symbol.


Solution

  • As the most probable scenario is that the Euro symbol will always be in the textfield and will be the first character, I would check if the range of characters to change is longer than 0 and starts at 0. (This will work regardless of the symbol in the first position)

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

    If however, the euro symbol is not always in the text field, you could check whether the user is deleting this symbol or not by getting a reference to the string the user is changing and checking whether this contains a euro symbol:

    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
    }