Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

ios - How to change SwiftUI TextField style after tapping on it?

I changed TextField style like this:

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

now I want it to change style when user taps on it.

My CustomTextFieldStyle is defined as:

  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))
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
TextField("Test", text: $name).textFieldStyle(tapflag ? CustomTextFieldStyle1() : CustomTextStyle2())

do you have an example of your own 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 enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...