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

标签 swift swiftui

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

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

代码如下:

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

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/57688242/

相关文章:

ios - 错误: Use of undeclared type BindableObject

ios - 推送通知 - Firebase

swift - xcodebuild : Returned an unsuccessful exit code

ios - 3D Touch UICollectionView insideUITableviewCell

swift - 在 SwiftUI 的 ForEach 中获取索引

ios - Swift Charts : . chartYScale 似乎只能以 100 为增量工作?

swiftui - 如何以编程方式触发 NavigationLink?

swiftui - 在 SwiftUI 中点击图像时出现意外行为

swift - 使用 Swift 枚举减少函数中的参数数量

swift - 服务器端 Swift : Navbar Toggle not working in Vapor 4 Leaf + Bootstrap