SwiftUI Textfield - 如何在编辑模式下将文本字段的背景颜色设置为清除

标签 swiftui textfield

为了适应我的其他控件,我的 TextField View 的框架的高度比文本本身更大。

标准 View 显示在图像顶部,并带有自定义占位符。

当我点击文本字段时,较小的文本区域本身具有灰色背景,如图像底部所示。

TextView example

如何将此文本背景设置为透明颜色?

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/

相关文章:

swiftui - 如何在 CommandGroup 中使用 CommandMenu?

ios - 在 SwiftUI 中创建包含 1000 个元素的列表时出现性能问题

完成后的 SwiftUI EditButton 操作

javascript - 在加载字段集时,我如何专注于我选择的文本字段

java - 如何在java中使用TextFormatter匹配true和false

java - 保存在 ArrayLists 中,但错误的输出写入文件

ios - 带有小数和长度的 Swift TextField 限制

swiftui - 如何在 SwiftData 和 SwiftUI 中使用 Swift 宏从数组中过滤对象

swift - SwiftUI 中的推送、弹出 View Controller 等效项

html - 基于 CSS 中的初始值设置的文本字段宽度