GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: TextField: Delay until user is done typing

Forums > SwiftUI

I have a SwiftUI TextField for the user to enter a value that is used by a custom Slider I built. Basically it shows an acceptable range for a value.

Because I'm using State variables, every time the user enters a number, the slider changes. This is problematic because the user could potentially have a value like 3000. With acceptable range of 2900 - 3100, you can see the problem when the slider updates when the user enters "3", then "30" and so on...

So how do I delay the update on the custom slider until the user is done typing?

Data Entry code

@State var collectedData: String = ""

  var body: some View {
    VStack{
      ComboSlider(testPoint: testPoint, observation: collectedData).padding()
      TextField("Data: ", text: $collectedData)

ComboSlider code (testPoint includes the min/max values and observation is from the TextField):

@ObservedObject var testPoint: TestPoint
var observation: String

//do a bunch of rectangles, geometries, and offsets based on observation

3      

One option is to use a computed property to limit the range of your data:

  var clippedData: String {
    let value = Int(collectedData) ?? 0
    return "\(min(3100, max(2900, value))"
  }

The textfield would still reference collectedData, but the slider would use the new variable.

3      

Thanks! Never thought of handling that way!

My slider allows data outside of the max/min range to provide visual cue to how far from acceptable values. So I can't use this clippingVal. But I'm going to apply the concept to at least keep it within an order of magnitude and that should clean it up!

3      

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

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.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.