0
4

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.

【SwiftUI】パスワード 表示 非表示 目玉

Last updated at Posted at 2021-02-22

これはなに

パスワード入力フォームにおいて目玉アイコンをクリックすると表示と非表示を切り替えられる実装と解説。

実装と解説

// パスワードの初期値
@State var password = ""

// メンバ変数でフラグを持たせる。trueならば非表示
@State var passHidden = true

// 中略

// textFieldと目玉アイコンを重ねて表示
ZStack {
    // textFieldと目玉アイコンを横に並べて表示
    HStack {
        if self.passHidden {
            // 非表示
            SecureField("入力してください", text: self.$password)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .frame(width: 320, height: 40, alignment: .center)
                // 重ねて表示するための位置調整
                .offset(x: 15, y:0)
            
        } else {
            // 表示
            TextField("入力してください", text: self.$password)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .frame(width: 320, height: 40, alignment: .center)
                // 重ねて表示するための位置調整
                .offset(x: 15, y:0)
        }
        Button(action: {self.passHidden.toggle() }) {
            // アイコンそれぞれの名前を指定
            Image(systemName: self.passHidden ? "eye.slash.fill": "eye.fill")
                // アイコンそれぞれの色を指定
                .foregroundColor((self.passHidden == true) ? Color.secondary : Color.gray)
        // 重ねて表示するための位置調整
        }.offset(x: -32, y:0)
    }
}

おわりです。
textFieldの大きさなどは適当にどうぞ。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?