LoginSignup
2
1

More than 3 years have passed since last update.

【Swift】ライブラリ "Material Components" の MDCOutlinedTextField を使ったTextField実装

Posted at

これはなに

マテリアルデザインのUIが簡単に実装できる Material Components を使ってこんな感じのTextFieldを作りたい。

8e206d4c9234c0106c809d47f2c61e79.gif

Material Componentsのインストール方法は省く。

実装してみる

41c5ba946265cc8c685e8ffddb57348a.png

StryboardのTextFieldを選択して MDCOutlinedTextField を設定する。
そしたらControllerにつなぐ。

LoginViewController.swift
class LoginViewController: UIViewController {

    // ユーザ名入力欄
    @IBOutlet weak var userNameTextField: MDCOutlinedTextField!

// 中略

TextFieldのプロパティを設定していく。

LoginViewController.swift
override func viewDidLoad() {
        super.viewDidLoad()

        userIdTextField.label.text = "ユーザーなまえ"
        userIdTextField.placeholder = "なまえをいれなさい"

        // TextFieldが選択されていない状態の枠と文字の色
        userIdTextField.setOutlineColor(.gray, for: .normal)
        userIdTextField.setFloatingLabelColor(.gray, for: .normal)

        // 編集中の枠と文字の色
        userIdTextField.setOutlineColor(.blue, for: .editing)
        userIdTextField.setFloatingLabelColor(.blue, for: .editing)
}

これで上記の動画のようなTextField実装できる。

問題点

――が、ここまではドキュメントを読めば書いてあったんだけど、 userIdTextField.label.text の部分、つまりここでいう『ユーザーなまえ』の部分の色を変える方法がなかなか見つからなかった(userIdTextField.label.textColor ではダメだった)。

解決策

userIdTextField.setNormalLabelColor(.gray, for: .normal)

29aef63b5023ea9509543814b6e11ab7.png

ハー、できてよかった( ;∀;)

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