Search code examples
ioscocoa-touchuitextfielduikit

Adding the "Clear" Button to an iPhone UITextField


How do you add that little "X" button on the right side of a UITextField that clears the text? I can't find an attribute for adding this sub-control in Interface Builder in the iPhone OS 2.2 SDK.

Note: In Xcode 4.x and later (iPhone 3.0 SDK and later), you can do this in Interface Builder.


Solution

  • 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