我想更改 TextField 的占位符颜色,但找不到相应的方法。
我尝试设置 foregroundColor
和 accentColor
,但它不会更改占位符颜色。
代码如下:
TextField("Placeholder", $text)
.foregroundColor(Color.red)
.accentColor(Color.green)
也许还没有这方面的 API?
最佳答案
(目前)还没有它的 api。 但你可以:
使用自定义 placeholder
修饰符将any view 显示为any other view 的持有者!例如:
TextField("", text: $text)
.placeholder(when: text.isEmpty) {
Text("Placeholder recreated").foregroundColor(.gray)
}
💡 这是一个简单的 ZStack
,您可以在 View
扩展中使用它,例如:
extension View {
func placeholder<Content: View>(
when shouldShow: Bool,
alignment: Alignment = .leading,
@ViewBuilder placeholder: () -> Content) -> some View {
ZStack(alignment: alignment) {
placeholder().opacity(shouldShow ? 1 : 0)
self
}
}
}
🎁 现在您可以将任何 样式应用于占位符,例如带有图像的渐变占位符:
✅ 如果你有兴趣,这里是 how to apply resizable gradient on any view
💡 简约的艺术
大多数情况下,您只需要传递一个字符串和一个灰色占位符,例如:
TextField("", text: $text)
.placeholder("Placeholder", when: text.isEmpty)
您可以为上面的扩展编写一个简单的包装器:
extension View {
func placeholder(
_ text: String,
when shouldShow: Bool,
alignment: Alignment = .leading) -> some View {
placeholder(when: shouldShow, alignment: alignment) { Text(text).foregroundColor(.gray) }
}
}
就这样😉
关于 swift 用户界面。如何更改 TextField 的占位符颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57688242/