为了适应我的其他控件,我的 TextField View 的框架的高度比文本本身更大。
标准 View 显示在图像顶部,并带有自定义占位符。
当我点击文本字段时,较小的文本区域本身具有灰色背景,如图像底部所示。
如何将此文本背景设置为透明颜色?
struct TestView: View {
@State var city: String
@State var street: String
var body: some View {
VStack{
ZStack(alignment: .center) {
if city.isEmpty { Text("Bitte Namen eingeben")
.font(.system(size: 24, weight: .heavy, design: .default))
.foregroundColor(Color( red: 1.0, green: 0.0, blue: 0.0, opacity: 0.3))
}
TextField("", text: self.$city)
.textFieldStyle(CustomTFStyle())
}
ZStack(alignment: .center) {
if street.isEmpty { Text("Bitte Strasse eingeben")
.font(.system(size: 24, weight: .heavy, design: .default))
.foregroundColor(Color( red: 1.0, green: 0.0, blue: 0.0, opacity: 0.3))
}
TextField("", text: self.$street)
.textFieldStyle(CustomTFStyle())
}
}
}
}
public struct CustomTFStyle : TextFieldStyle {
public func _body(configuration: TextField<Self._Label>) -> some View {
configuration
.accentColor(.black)
.frame(width: 300, height: 70, alignment: .center)
.border(Color.gray, width: 4)
.font(.system(size: 30, weight: .heavy, design: .default))
.clipShape(RoundedRectangle(cornerRadius: 12))
.shadow(radius: 12)
.foregroundColor(.black)
}
}
最佳答案
我的 rootview 的 init 方法中的“UIScrollView.appearance().backgroundColor = .lightGray”也会影响 Textfield 行为。删除这一行就可以了。
关于SwiftUI Textfield - 如何在编辑模式下将文本字段的背景颜色设置为清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59394088/