我想更改TextField的占位符颜色,但找不到它的方法。
我试图设置foregroundColor
和accentColor
,但是它不会改变占位符的颜色。
以下是代码:
TextField("Placeholder", $text)
.foregroundColor(Color.red)
.accentColor(Color.green)
也许这还没有API呢?
发布于 2019-08-29 18:13:51
它没有api (目前为止)。,但你可以
使用自定义placeholder
修饰符显示任意视图作为的持有者,任何其他视图!例如:
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) }
}
}
简单得不得了
发布于 2020-04-05 10:49:32
最终,将内容嵌入到ViewModifier中的ZStack更优雅,代码更少:
public struct PlaceholderStyle: ViewModifier {
var showPlaceHolder: Bool
var placeholder: String
public func body(content: Content) -> some View {
ZStack(alignment: .leading) {
if showPlaceHolder {
Text(placeholder)
.padding(.horizontal, 15)
}
content
.foregroundColor(Color.white)
.padding(5.0)
}
}
}
用法:
TextField("", text: $data)
.modifier(PlaceholderStyle(showPlaceHolder: data.isEmpty,
placeholder: "My Placeholder"))
发布于 2020-07-17 08:29:47
这是对@jfk's answer的一点修改,我们可以为view
创建一个扩展,以简化主视图中的修饰符代码,也可以用于Text
和Image
。
struct PlaceHolder<T: View>: ViewModifier {
var placeHolder: T
var show: Bool
func body(content: Content) -> some View {
ZStack(alignment: .leading) {
if show { placeHolder }
content
}
}
}
extension View {
func placeHolder<T:View>(_ holder: T, show: Bool) -> some View {
self.modifier(PlaceHolder(placeHolder:holder, show: show))
}
}
在TextField中的使用:
将这行代码.placeHolder(Text("Your placeholder"), show: text.isEmpty)
作为viewModifier
添加到TextField
中。
TextField("", text: $text, onEditingChanged: { (changing) in
print("Changing: \(changing)")
}, onCommit: {
print("Committed!")
})
.placeHolder(Text("Your placeholder"), show: text.isEmpty)
在图像中的使用:
此外,正如@EmilioPelaez所建议的,我修改了代码以支持ex的任何视图的占位符。Image
就像下面这样。
Image("your_image")
.placeHolder(Image("placeholder_image"), show: true)
https://stackoverflow.com/questions/57688242
复制相似问题