Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Simplify .onChange Modifier for Many TextFields

Tags:

xcode

ios

swiftui

I'm searching for a way to simplify/refactor the addition of .onChange(of:) in a SwiftUI view that has MANY TextFields. If a solution were concise, I would also move the modifier closer to the appropriate field rather than at the end of, say, a ScrollView. In this case, all of the .onChange modifiers call the same function.

Example:

.onChange(of: patientDetailVM.pubFirstName) { x in
    changeBackButton()
}
.onChange(of: patientDetailVM.pubLastName) { x in
    changeBackButton()
}
// ten+ more times for other fields

I tried "oring" the fields. This does not work:

.onChange(of:
            patientDetailVM.pubFirstName ||
            patientDetailVM.pubLastName
) { x in
    changeBackButton()
}

This is the simple function that I want to call:

func changeBackButton() {
    withAnimation {
        showBackButton = false
        isEditing = true
    }
}

Any guidance would be appreciated. Xcode 13.2.1 iOS 15

like image 524
JohnSF Avatar asked Nov 20 '25 06:11

JohnSF


1 Answers

Why not just use a computed var?

@State private var something: Int = 1
@State private var another: Bool = true
@State private var yetAnother: String = "whatever"

var anyOfMultiple: [String] {[
    something.description,
    another.description,
    yetAnother
]}

var body: some View {
    VStack {
        //
    }
    .onChange(of: anyOfMultiple) { _ in
        //
    }
}
like image 52
Swiftly Avatar answered Nov 22 '25 21:11

Swiftly