Search code examples
iosswiftiphoneswift2uitextfield

How to clear the text field automatically


I have a question about UITextField() in Swift. How can I clear the text in the text field when I click on it?

My textField.text = "0". I want to automatically remove the number "0" when I click on the text field:

import UIKit
class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var lbltext: UILabel!
    @IBOutlet var scrolview1: UIScrollView!
    @IBOutlet var fi: UITextField!
    @IBOutlet var scrolviewus: UIScrollView!
    @IBOutlet var counterLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        fi.text = "0"
       }

       override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()
         // Dispose of any resources that can be recreated.
       }

       @IBAction func button(sender: AnyObject) {
        lbltext.numberOfLines = 0
        lbltext.text! = lbltext.text! + "\n" + fi.text! + "\n" + "---  "
    }
 }

Solution

  • Use this method,

    If you want to manually clear the text field use this code:

    textField.text = ""
    

    If you want the text field to empty when you begin editing, use the delegate method below:

    func textFieldDidBeginEditing(textField: UITextField) {
        textField.text = ""
    }
    

    If you are using multiple text fields, use the method below:

    func textFieldDidBeginEditing(textField: UITextField) { 
        if (textField == oneTextField) {
           textField.text = ""
        } 
        else if (textField == anotherTextField) {
           // Perform any other operation
        } 
    }