|
I have 2 TextFields: --- x2 --- I want to perform simple calculations: string1 x 2 = string2. I am using .onChange modifier, so if you type first number it is multiplied by 2 and result is printed in second TextField. You can go the other way around and type string2 and it will be divided by 2 and result will be printed in the first TextField. Now because both TextFields have .onChange, it gets triggered few times (3 in this case). After changing string1, string2 gets updated. And as it changed, .onChange of string2 is triggered and later the same with .onChange of string1. Please run this example code and check what gets printed in console:
Question: How to make .onChange conditional so it runs only once? To be precise, I want to execute .onChange on first input ONLY when I edit first input. And execute .onChange on second input ONLY when I edit second input. Probably it will be easy with .onFocus in iOS 15. But how to do it in iOS 14? |
|
OK, I've figured it out :) I needed two variables, one per TextField: isFocused1, isFocused2. Each of them changes to true with onEditingChanged. And each onChange has if condition that checks if isFocused for this TextField is true. Now onChange is triggered only if each TextField is being edited. I have added changing background colors to visualize focus changes. Working code:
|
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.