[SwiftUI]SecureFieldのプレースホルダーの色を変えるには?

SwiftUI

どうも、ちょげ(@chogetarou)です。

SwiftでSecureFieldのプレースホルダーの色を変える方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

SecureFieldのプレースホルダーの色を変えるには、モディファイアを使います。

まず、カスタムモディファイアを用意します。

struct PlaceFolder: ViewModifier {
    let text : String //SecurdFieldのテキストを受け取る
    func body(content: Content) -> some View {
        content    
    }
}

次に、モディファイアのbodyメソッド内で、テキストが空の時に、SecureFieldの上にTextを表示するようにします。

また、Textの文字列にはプレースホルダーを指定し、foregroundColor修飾子でプレースホルダーの色を設定します。

struct PlaceFolder: ViewModifier {
    let text : String

    func body(content: Content) -> some View {
        ZStack {
            content
            if text.isEmpty {
                Text("プレースホルダー")
                    .foregroundColor(color) //プレースホルダーの色
            }
        }
            
    }
}

最後に、用意したモディファイアをSecureFieldに適用します。

SecureField("", text: $text)
    .modifier(
        PlaceFolder(text: self.text)
    )

使用例

以下は、使用例です。


struct ContentView: View {
    @State var password = ""
    var body: some View {
        
        VStack{
            SecureField("", text: $password)
                .modifier(
                    PlaceFolder(text: self.password, placeHolder: "パスワード",color: Color.gray)
                )
                .padding()
        }
    }
}

struct PlaceFolder: ViewModifier {
    let text : String
    let placeHolder : String
    let color : Color
    func body(content: Content) -> some View {
        ZStack {
            content
            if text.isEmpty {
                Text(placeHolder)
                    .foregroundColor(color)
            }
        }
            
    }
}

コメント

タイトルとURLをコピーしました