Ios 如何调整文本字段占位符颜色:SwiftUI
我发现我可以像这样在swift中自定义文本字段样式Ios 如何调整文本字段占位符颜色:SwiftUI,ios,swift,swiftui,textfield,Ios,Swift,Swiftui,Textfield,我发现我可以像这样在swift中自定义文本字段样式 struct BottomLineTextFieldStyle: TextFieldStyle { func _body(configuration: TextField<Self._Label>) -> some View { VStack() { configuration Rectangle() .frame(hei
struct BottomLineTextFieldStyle: TextFieldStyle {
func _body(configuration: TextField<Self._Label>) -> some View {
VStack() {
configuration
Rectangle()
.frame(height: 1, alignment: .bottom)
.foregroundColor(Color.white)
}
}
}
然而,我也想改变占位符的颜色,但我不能
所以,我的问题是如何定制textfield的占位符颜色?
请帮助我,谢谢你的阅读
所以,我的问题是如何定制textfield的占位符颜色
不幸的是,到目前为止,无法更改标准文本字段占位符的颜色。然而,它是有可能以某种方式修改它,所以,我认为值得张贴
在下面的演示文本字段颜色的修改,密码的一个是默认的。
struct BottomLineTextFieldStyle:TextFieldStyle{
func_body(配置:TextField)->一些视图{
VStack(){
配置
.colorMultiply(.red)
.foregroundColor(.red)
矩形()
.框架(高度:1,对齐方式:底部)
.foregroundColor(.red)
}
}
}
您还不能更改占位符的默认颜色。但是,可以通过使用UITextField
或UITextView
编写自定义TextField
来实现。下面是一个示例,我使用UITextView
创建了一个自定义TextArea
视图,可以在其中设置占位符的自定义颜色。请参见下面我在makeUIView(:)
编辑:
上述文本区域可在视图中使用,如下所示:
TextArea(placeholder: textValue, text: $textValue)
我明白了。谢谢如何使用此文本区域?您能给我举个使用示例吗?如果我想使用“下划线”形状文本字段而不是方框形状,我必须在哪里编辑此代码?您可以编辑TextArea的makeUIView方法,以根据您的具体需要返回UIEdtField。请注意,这里使用的是UIKit元素而不是SwiftUI元素。您可以在此处阅读更多信息:
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)
}
}
}
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)