如何解决TextField前面的Text阻止在SwiftUI中进行编辑
因此,我希望我的文本字段具有可自定义的占位符文本,因此我决定在文本字段前面的ZStack中放置一个Text()元素。唯一的问题是,此Text()项会阻止对其后面的文本字段的选择(也就是,当我单击要单击TextField的占位符时)。不幸的是,此Text()元素阻止了点击。我尝试使用.allowsHitTesting()属性,如下所示,但这也没有用,而且我不确定为什么。
struct ContentView: View {
@State var text: String = ""
var body: some View {
ZStack {
TextField("",text: self.$text)
.background(Color.red)
.foregroundColor(Color.white)
if text.isEmpty {
Text("Placeholder")
.allowsHitTesting(false)
}
}
}
}
解决方法
看看这是否符合您的需求:
struct ContentView: View {
@State var text = ""
var body: some View {
ZStack(alignment: .leading) {
if text.isEmpty { Text("Placeholder")
.foregroundColor(.red)
.background(Color.yellow)
}
TextField("",text: $text)
.background(text.isEmpty ? Color.clear : Color.yellow)
}
}
}
,
可以使用自定义文本字段样式完成。
这里是解决方案的演示(或可以调整参数)。经过Xcode 12 / iOS 14测试(边框仅用于可见性)
struct PlaceholderStyle: TextFieldStyle {
let isActive: Bool
var placeholder = "Placeholder"
var color = Color.white
var backgrond = Color.red
func _body(configuration: TextField<_Label>) -> some View {
Text("\(isActive ? placeholder : "")")
.foregroundColor(isActive ? color : .clear)
.background(isActive ? backgrond : .clear)
.frame(maxWidth: .infinity,alignment: .leading)
.overlay(configuration)
}
}
struct DemoView: View {
@State private var text = ""
var body: some View {
TextField("",text: $text)
.border(Color.gray).padding(.horizontal)
.textFieldStyle(PlaceholderStyle(isActive: text.isEmpty))
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。