我想更改 TextField 的占位符颜色,但找不到方法。
我尝试设置 foregroundColor
和 accentColor
,但它不会更改占位符颜色。
这是代码:
TextField("Placeholder", $text)
.foregroundColor(Color.red)
.accentColor(Color.green)
也许还没有可用的 API?
最佳答案
目前还没有对应的 API。 但是你可以:
使用自定义占位符
修饰符将任何 View 显示为任何其他 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/59173444/