参考
how to erase or clear UITextField
環境
- Xcode8
- Xcode7でも大丈夫
- Swift 3でも大丈夫
- 2.3でも大丈夫
- ObjectivCでも大丈夫
手順
UITextFieldにあらかじめ入力されている文字を、UIButtonを押したら一発で全部消えるようにしたかったです。簡単に出来ました、から文字を代入するだけです。一応、実装の方法を説明すると、まずUIButtonとUITextFieldを用意します。
UITextFieldをOutletで参照できるように定義して、UIButtonをActionメソッドで定義します。UITextFieldあらかじめ文字を入れておいて、UIButtonのアクションメソッドの中に UITextField名.text = ""
みたいな感じで空文字を代入しておけば、UIButtonをタップしたらUITextFieldの文字が全部消えます
実装
ViewController
import UIKit
class ViewController: UIViewController {
//テキストフィールドをoutletで定義する
@IBOutlet var textDelet: UITextField!
//文字を消すボタンを押した時の処理
@IBAction func goneButton(_ sender: UIButton) {
//空文字を代入するので消えます
textDelet.text = ""
}
@IBAction func tapGreen(_ sender: UIButton) {
view.backgroundColor = UIColor.green
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//あらかじめテキストフィールドに表示しておく文字
textDelet.text = "text"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}