0
1

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 5 years have passed since last update.

Swift UITextField

Posted at

今回はTextFieldの使い方です

TextFieldは選択すると文字を入力できるものですね

今回もUIの接続をしたところから解説していきます

ViewController.swift
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func button(_ sender: Any) {
    }   
}

接続後のコードです

まずはtextFieldに入力した文字をbuttonを押した時にlabelに表示するようにしていきましょう

ViewController.swift
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func button(_ sender: Any) {
        label.text = textField.text
    }   
}

これでlabelに文字を表示できます
しかし、このままではキーボードが表示されたままになってしまいます
なので、キーボードのreturnを押した時にキーボードを閉じるようにします

ViewController.swift
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self   //追記
    }

    @IBAction func button(_ sender: Any) {
        label.text = textField.text
    }   
}

//以下を追記
extension ViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
    }
}

textField.delegate = selfでdelegateを設定してあげます
delegateについてはいづれ記事を書きます
delegateを設定するとUITextFieldDelegateを継承して!と言われるのでfixを押してもいいですし、extensionで拡張してから書いてもいいです
あとは決まり文句みたいなものだと思って書いてください

雑な解説になってしまいすみません
今回はこれで終わります

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?