如何清除文本字段?

X.B*_*OZO 13 iphone ios swift swift2.2

我对swift中的TextFiled有疑问

我如何在单击它时清除TextFiled中的文本

我的textfiled.text ="0"

我想当我点击textfiled删除数字"0"automatica

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" + "---  "
    }
 }
Run Code Online (Sandbox Code Playgroud)

Iyy*_*avi 31

使用这种方法,

如果要手动清除文本字段,请使用以下代码:

textField.text = ""
Run Code Online (Sandbox Code Playgroud)

如果要在开始编辑时将文本字段清空,请使用下面的委托方法:

func textFieldDidBeginEditing(textField: UITextField) {
    textField.text = ""
}
Run Code Online (Sandbox Code Playgroud)

如果您使用多个文本字段,请使用以下方法:

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


小智 6

您可以轻松地快速清除 TextField

emailTextField.text?.removeAll()
passwordTextField.text?.removeAll()
confirmPasswordTextField.text?.removeAll()
Run Code Online (Sandbox Code Playgroud)


bri*_*one 5

只需使用textFieldDidBeginEditing方法来处理焦点变化和清除文本.

func textFieldDidBeginEditing(textField: UITextField) {
    textField.text = ""
}
Run Code Online (Sandbox Code Playgroud)