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

ali*_*_ix 5 textfield ios swift swiftui

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

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

            Rectangle()
                .frame(height: 1, alignment: .bottom)
                .foregroundColor(Color.white)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

用法

TextField("placeholder", text: $value).textFieldStyle(BottomLineTextFieldStyle()).foregroundColor(.white)
Run Code Online (Sandbox Code Playgroud)

不过我也想改变占位符颜色,但我不能。

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

Ish*_*eet 4

您尚无法更改占位符的默认颜色。TextField但是,您可以通过使用UITextField或编写自定义来实现它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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

上面的文本区域可以在视图中使用,如下所示:

 TextArea(placeholder: textValue, text: $textValue)
Run Code Online (Sandbox Code Playgroud)