brandonscript brandonscript - 5 months ago 19
Objective-C Question

How can I force a UITextField to only support lowercase characters?

I want to override the key pressed event to force that, even when a capital key is pressed, the resulting output is still lowercase.

Answer

Solution is to add a selector for textFieldDidChange:

[self addTarget:self
                  action:@selector(textFieldDidChange:)
        forControlEvents:UIControlEventEditingChanged];

And in the textFieldDidChange event, add the following:

- (void)textFieldDidChange:(UITextField*)textField {
    textField.text = [textField.text lowercaseString];
}

Or you can use the Interface Builder @IBAction Editing Changed

Swift 2 version:

@IBAction func textChanged(sender: UITextField) {
    sender.text = sender.text?.lowercaseString
}