如何调整TextField占位符颜色:SwiftUI

时间:2020-04-21 07:23:17

标签: ios swift swiftui textfield

我发现我可以像这样快速地自定义TextField样式。

struct BottomLineTextFieldStyle: TextFieldStyle {
    func _body(configuration: TextField<Self._Label>) -> some View {
        VStack() {
            configuration

            Rectangle()
                .frame(height: 1, alignment: .bottom)
                .foregroundColor(Color.white)
        }
    }
}

这使我可以使用“下划线形状样式”文本字段。

用法

TextField("placeholder", text: $value).textFieldStyle(BottomLineTextFieldStyle()).foregroundColor(.white)

但是我也想更改占位符颜色,但是我不能。

所以,我的问题是如何自定义文本字段的占位符颜色? 请帮助我,谢谢阅读。

2 个答案:

答案 0 :(得分:1)

您还不能更改占位符的默认颜色。但是,您可以通过使用TextFieldUITextField编写自定义UITextView来实现。这是一个示例,其中我使用TextArea创建了自定义UITextView视图,可以在其中为占位符设置自定义颜色。请在下面的makeUIView(_:)

中查看我的评论
struct TextArea: UIViewRepresentable {
    @State var placeholder: String
    @Binding var text: String

    func makeCoordinator() -> Coordinator {
        Coordinator(self, placeholder: placeholder)
    }

    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.text = placeholder

        // Here you can set the color for placeholder text as per your choice. 
        textView.textColor = .lightGray

        textView.delegate = context.coordinator
        return textView
    }

    func updateUIView(_ textView: UITextView, context: Context) {
        if !text.isEmpty {
            textView.text = text
            textView.textColor = .black
        }
    }

    class Coordinator: NSObject, UITextViewDelegate {
        var textArea: TextArea
        var placeholder: String

        init(_ textArea: TextArea, placeholder: String) {
            self.textArea = textArea
            self.placeholder = placeholder
        }

        func textViewDidBeginEditing(_ textView: UITextView) {
            if textView.textColor == .lightGray {
                textView.text = nil
                textView.textColor = .black
            }
        }

        func textViewDidEndEditing(_ textView: UITextView) {
            if textView.text.isEmpty {
                textView.text = placeholder
                textView.textColor = UIColor.lightGray
            }
        }
    }
}

编辑:

上面的文本区域可以在这样的视图中使用:

 TextArea(placeholder: textValue, text: $textValue)

答案 1 :(得分:0)

所以,我的问题是如何自定义文本字段的占位符颜色?

不幸的是,到目前为止,无法更改标准TextField占位符的颜色。但是可以以某种方式对其进行修改,因此,我认为值得发布

在下面的演示TextField颜色的修改中,默认设置为Password。 demo demo2

struct BottomLineTextFieldStyle: TextFieldStyle {
    func _body(configuration: TextField<Self._Label>) -> some View {
        VStack() {
            configuration
                .colorMultiply(.red)
                .foregroundColor(.red)

            Rectangle()
                .frame(height: 1, alignment: .bottom)
                .foregroundColor(.red)
        }
    }
}