简体   繁体   English

点击后如何更改 SwiftUI TextField 样式?

[英]How to change SwiftUI TextField style after tapping on it?

I changed TextField style like this:我像这样更改了 TextField 样式:

TextField("Test", text: $name).textFieldStyle(CustomTextFieldStyle())

now I want it to change style when user taps on it.现在我希望它在用户点击时改变样式。

My CustomTextFieldStyle is defined as:我的 CustomTextFieldStyle 定义为:

  public struct CustomTextFieldStyle : TextFieldStyle {
    public func _body(configuration: TextField<Self._Label>) -> some View {
        configuration
            .font(.callout)
            .padding(10)
            .background(
                RoundedRectangle(cornerRadius: 4)
                    .strokeBorder(SBGreen, lineWidth: 2))
    }
}
TextField("Test", text: $name).textFieldStyle(tapflag ? CustomTextFieldStyle1() : CustomTextStyle2())

do you have an example of your own TextStyle?你有你自己的 TextStyle 的例子吗? Please, share it!请分享它!

UPDATE更新

you are better to use some parameter with your style and bind it to "parent" View您最好在样式中使用一些参数并将其绑定到“父”视图

import SwiftUI

struct ContentView: View {

    @State private var email = ""
    @State private var editing = false
    var body: some View {
        TextField("Email", text: self.$email, onEditingChanged: { edit in
            self.editing = edit
        })
            .textFieldStyle(MyTextFieldStyle(focused: $editing)).font(.title).border(Color.blue)
    }
}

struct MyTextFieldStyle: TextFieldStyle {
    @Binding var focused: Bool
    func _body(configuration: TextField<Self._Label>) -> some View {
        configuration
        .padding(10)
        .background(
            RoundedRectangle(cornerRadius: 10, style: .continuous)
                .stroke(focused ? Color.red : Color.gray, lineWidth: 3)
        ).padding()
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

the result looks like结果看起来像在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM