0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

UITextFieldをタップ時、任意のTextを追加する。

Posted at

完成形はこんな感じ

F7736CD1-C3D0-4E3B-8689-68E68B9CE3CE_1_201_a.jpeg

機能説明

  • 撤去する日付のUITextFieldをタップした時に、年月日が表示されます。

コードと簡単解説

  • .addTarget(target: Any?, action: Selector, for: UIControl.Event)を用います。

  • UIControl.Eventの箇所には、UITextFieldをタップした時にactionの処理を使いたいので,.allTouchEventsを今回使用しています。

  • actionの処理は、UITextFieldをタップした時にUITextField.Textが空だったら、年月日をUITextField.Textに表示します。

  • なぜ、UITextField.Textが空の時なのかは、希望の入力値を入力した後にUITextFieldをタップしたらUITextField.textが「年月日」だけになってしまいますので、それを防ぐ為です。


  @IBOutlet weak var deadlineDayTextField: UITextField!

  override func viewDidLoad() {
           super.viewDidLoad()

  deadlineDayTextField.addTarget(self, action: #selector(addYearMonthDay), for: .allTouchEvents) 

  }
  
      @objc func addYearMonthDay(_ sender:UITextField){
        
        if sender.text == ""{
            
            sender.text = "年月日"
            
        }
        
    } 

終わり

今日は、年月日を入力する時に何度も「年月日」を入力したくなくて、簡単ですが書いてみました。
ご指摘、ご質問などありましたら、コメントまでお願い致します。

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?