是否可以更改SwiftUI.TextField
中的占位符文本颜色?
答案 0 :(得分:7)
SwiftUI不支持AttributedString
,并且还没有直接的支持。 但是您可以使用以下几行代码构建自定义占位符:
使用ZStack
并自己实现一个占位符:
var body: some View {
ZStack(alignment: .leading) {
if text.isEmpty {
Text("Placeholder")
.foregroundColor(.red)
}
TextField("", text: $text)
}
}
因此,您可以占位符进行任何自定义操作。
您始终可以创建自己的自定义View
以便在任何地方使用:
struct CustomTextField: View {
var placeholder: Text
@Binding var text: String
var editingChanged: (Bool)->() = { _ in }
var commit: ()->() = { }
var body: some View {
ZStack(alignment: .leading) {
if text.isEmpty { placeholder }
TextField("", text: $text, onEditingChanged: editingChanged, onCommit: commit)
}
}
}
使用(TextField
和占位符):
struct ContentView: View {
@State var text = ""
var body: some View {
CustomTextField(
placeholder: Text("placeholder").foregroundColor(.red),
text: $text
)
}
}
答案 1 :(得分:0)
要设置占位符,请将其作为初始化程序的一部分从hackingwithswift传入
struct ContentView: View {
@State private var emailAddress = ""
var body: some View {
TextField("johnnyappleseed@apple.com", text:
$emailAddress)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
}