SwiftUI. How to change the placeholder color of the TextField?

后端 未结 4 1466
臣服心动
臣服心动 2020-12-29 19:38

I want to change the placeholder color of the TextField, but I can\'t find a method for it.

I tried to set foregroundColor and accentColor,

4条回答
  •  余生分开走
    2020-12-29 20:19

    It's a bit modification for the @jfk's answer, we can create an extension for view to simplify the modifier code inside the main view and also it can be used for Text and Image.

    struct PlaceHolder: ViewModifier {
        var placeHolder: T
        var show: Bool
        func body(content: Content) -> some View {
            ZStack(alignment: .leading) {
                if show { placeHolder }
                content
            }
        }
    }
    
    extension View {
        func placeHolder(_ holder: T, show: Bool) -> some View {
            self.modifier(PlaceHolder(placeHolder:holder, show: show))
        }
    }
    

    Usage in TextField:

    Add this line of code .placeHolder(Text("Your placeholder"), show: text.isEmpty) as a viewModifier to TextField.

    TextField("", text: $text, onEditingChanged: { (changing) in
        print("Changing: \(changing)")
    }, onCommit: {
        print("Committed!")
    })
        .placeHolder(Text("Your placeholder"), show: text.isEmpty)
    

    Usage in Image:

    Further more, as @EmilioPelaez suggested, I modified the code to support placeholder for any view for ex. Image like below.

    Image("your_image")
        .placeHolder(Image("placeholder_image"), show: true)
    

提交回复
热议问题