1

I'm trying to create a TextField with a line below it, for that I used a Divide as suggested in this answer and I added a .onTapGesture() to it to change the Divider color, however that's a component that's embedded in another view.

In my ContentView I have a Button and my UnderscoredTextField and they are contained inside a HStack and it's contained inside a Background component (taken from this answer) to be able to dismiss the keyboard programmatically, but I'd like to be able to change the @State var isActive variable inside the UnderscoredTextField when that happens, but as I'm new to SwiftUI I'm not quite sure how to achieve this.

import SwiftUI

struct ContentView: View {
    var body: some View {
        Background {
            UnderscoredTextField(phoneNumber: "")
        }.onTapGesture {
            self.hideKeyboard()
            //How to tell my UnderscoreTextField's isActive variable to change
        }
    }
}

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

import SwiftUI

struct UnderscoredTextField: View {
    @State var phoneNumber: String
    @State var isActive: Bool = false
    
    var body: some View {
        VStack {
            TextField("12345678", text: $phoneNumber)
                .keyboardType(.phonePad)
                .onTapGesture {
                    self.isActive = true
            }
            Divider()
                .padding(.horizontal)
                .frame(height: 1)
                .background(isActive ? Color.red : Color.gray)
        }
    }
}

struct UnderscoredTextField_Previews: PreviewProvider {
    static var previews: some View {
        UnderscoredTextField(phoneNumber: "12345678")
    }
}

This is what it looks like when I hide the keyboard, but I'd like to switch it back to gray

enter image description here

Frakcool
  • 10,915
  • 9
  • 50
  • 89

1 Answers1

1

If I understood correctly it is enough to use onEditingChanged, like below

var body: some View {
    VStack {
        TextField("12345678", text: $phoneNumber, onEditingChanged: {
                self.isActive = $0     // << here !!
        }).keyboardType(.phonePad)
        Divider()
            .padding(.horizontal)
            .frame(height: 1)
            .background(isActive ? Color.red : Color.gray)
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690