LoginSignup
6
3

More than 3 years have passed since last update.

【Swift】TextFieldのスタイルを入力状態で変更する

Posted at

はじめに:TextFieldのスタイル

UITexitFieldでは枠線のスタイルを4種類(none, line, bezel, round)の中から設定することができます
StoryBoardから指定する場合はAttributes Inspectorで変更:
コードで指定する場合はtextField.borderStyle = .noneといったように記述します。

それぞれの見た目は以下の感じ

  • none スクリーンショット 2019-09-23 11.50.53.png

  • line スクリーンショット 2019-09-23 11.51.24.png

  • bezel スクリーンショット 2019-09-23 11.51.40.png

  • round スクリーンショット 2019-09-23 11.51.53.png

作りたいもの

noneにしておくと見た目的にはLabelチックにも扱えるので、普段はnoneで表示しておいて、入力状態の場合はスタイルをroundに変更するTextFieldを作ろうと思います。
ezgif.com-video-to-gif (1).gif

実装

EditingStyleChangeTextFieldというカスタムクラスを作成します。
UITextFieldDelegateを継承して、テキストフィールド編集でのイベントハンドリングができるようにします。

EditingStyleChangeTextField.swift
import UIKit

class EditingStyleChangeTextField: UITextField, UITextFieldDelegate {

    override func awakeFromNib() {
        self.delegate = self
        // 初期スタイルを指定
        self.borderStyle = .none
        self.backgroundColor = .clear
        self.textAlignment = .center
        self.returnKeyType = .done
        self.text = "Sample"
    }

    /// テキストフィールド入力状態後
    func textFieldDidBeginEditing(_ textField: UITextField) {
        // スタイルを編集中のものに変更
        self.borderStyle = .roundedRect
        self.backgroundColor = .white
    }

    /// リターンキー入力時
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // キーボードを閉じる
        textField.resignFirstResponder()
        return true
    }

    /// フォーカスが外れる前
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        // 入力チェック
        if(self.text == ""){
            self.backgroundColor = .red
            return false
        }
        else{
            return true
        }
    }

    /// フォーカスが外れた後
    func textFieldDidEndEditing(_ textField: UITextField) {
        // スタイルを元に戻す
        self.borderStyle = .none
        self.backgroundColor = .clear
    }
}

StoryBoardで適当にTextFieldを置きます
スクリーンショット 2019-09-23 12.20.11.png

TextFieldにCustom Classを当てます
スクリーンショット 2019-09-23 12.21.42.png

ビルド通したら完了👍
Simulator Screen Shot - iPhone 11.png

6
3
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
6
3