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" + "--- " } } 46 Answers
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 } } 8You can easily clear the TextField in swift
emailTextField.text?.removeAll() passwordTextField.text?.removeAll() confirmPasswordTextField.text?.removeAll() 2Simply use textFieldDidBeginEditing method to handle focus change, and clear text.
func textFieldDidBeginEditing(textField: UITextField) { textField.text = "" } 0func textFieldDidBeginEditing(textField: UITextField) { if fi.text == "0" { fi.text = "" } } 0There are a couple of ways you can solve this problem, depending on what you're looking for. The first is to use a placeholder instead of setting the text to 0. A placeholder will disappear whenever the user starts typing and reappear if they type nothing in:
fi.placeholder = "0" if you want the 0 to be the value and not just a placeholder, there are lots of built in methods to track editing/entering/returning/etc of a textfield. This does require implementation of the UITextFieldDelegate however, which it appears you have already done.
var isFirstTime = true override viewDidLoad() { super.viewDidLoad() fi.delegate = self } func textViewDidBeginEditing(textView: UITextView) { isFirstTime = false if fi.text == "0" { fi.text = "" } } func textViewDidEndEditing(textView: UITextView) { if fi.text.isEmpty { fi.text = "0" isFirstTime = true } } The is first time var is only present so that the user can type 0 if they choose. If the user should not be able to type 0, then it may be removed.
2func textFieldDidBeginEditing(textField: UITextField) { fi.text = "" } func textFieldDidEndEdition(textField: UITextField) { if fi.text isEqualToString:@"" { fi.text = @"" } } 0