gpt4 book ai didi

swift 用户界面。如何更改 TextField 的占位符颜色?

转载 作者:行者123 更新时间:2023-11-29 05:16:07 25 4
gpt4 key购买 nike

我想更改 TextField 的占位符颜色,但找不到方法。

我尝试设置 foregroundColoraccentColor,但它不会更改占位符颜色。

这是代码:

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)
}

Demo1

💡这是一个简单的 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
}
}
}

🎁 现在您可以将任何类型的样式应用于占位符,例如带有图像的渐变占位符:

Demo2

✅ 如果您有兴趣,这里是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com