Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change SwiftUI TextField style after tapping on it?

Tags:

ios

swift

swiftui

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))
    }
}
like image 559
Daniel Kubicek Avatar asked Feb 24 '20 15:02

Daniel Kubicek


1 Answers

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

like image 146
user3441734 Avatar answered Nov 18 '22 09:11

user3441734