LoginSignup
1
0

More than 5 years have passed since last update.

iOS - UIButtonを押してUITextFieldの文字を一発で消す方法

Last updated at Posted at 2017-02-02

参考

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.
    }


}


1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0