Tim Dietrich

Custom Software Developer

Home Services Portfolio Blog About Contact Newsletter

Swift: Setting Focus to a Text Field

When displaying a form, it's often nice to automatically set the focus to the first field. It's convenient for users, because it saves them a click.

In Javascript, you would set focus using the focus method. For example:

document.getElementById("someTextField").focus();

It's also possible to set focus to a field in Swift, and it's actually easy to do. However, how you do it might not be obvious.

To set the focus to a field, you first need to setup an IBOutlet for the field. Then, in the view controller's "viewDidLoad" method, you set the field as the first responder.

Here's a code snippet that shows the technique:


class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        
        // Set focus to the text field.
        textField.becomeFirstResponder()
        
    }

}

A Swift / Xcode project that demonstrates the technique is available here.