Adding the "Clear" Button to an iPhone UITextField Adding the "Clear" Button to an iPhone UITextField ios ios

Adding the "Clear" Button to an iPhone UITextField


This button is a built-in overlay that is provided by the UITextField class, but as of the iOS 2.2 SDK, there isn't any way to set it via Interface Builder. You have to enable it programmatically.

Add this line of code somewhere (viewDidLoad, for example):

Objective-C

myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;

Swift 5.0

myUITextField.clearButtonMode = .whileEditing


You can also set this directly from Interface Builder under the Attributes Inspector.

enter image description here

Taken from XCode 5.1


Swift 4+:

textField.clearButtonMode = UITextField.ViewMode.whileEditing

or even shorter:

textField.clearButtonMode = .whileEditing