johnjay22113 johnjay22113 - 6 months ago 11
iOS Question

How can i make a function for a certain textfield?

This code allows the users to type in certain characters only:

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

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

}


How can i make it so that it allows a just one textfield called "txtField1"?

Answer

Assign a value to the tag on your textfield that is unique to it (for example, 1).

txtField1.tag = 1

Then, update your method like this:

func textField(
    textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
                                  replacementString string: String)
    -> Bool
{
    if textField.tag == 1 {
        let set = NSCharacterSet(charactersInString: allowedChars)

        let filtered = string
            .componentsSeparatedByCharactersInSet(set)
            .joinWithSeparator("")
        return filtered != string
    }

    return true
}

You can also omit the ; in Swift.