UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Numeric TextField maximum and minimum values

Forums > SwiftUI

Hi all.

I'm trying to implement some TextFields that accept any number in a desired range. This is, if the user is entering an age, I'd like it to be from 0 to 100, for example. However, I don't know how to control this in a TextField.

What I've tried is using didSet or willSet within the variable to check those conditions and set the minimum or maximum values in case the new value exceeds the range, but it doesn't do anything. Other workaround I though about is using onChange(of:) to check that the value is in that range, but it doesn't reflect any changes either.

Any other workarounds?

Thank you in advance.

2      

Why do you not use a Picker for a closed range? However if what the age I would use DatePicker then calculate the birthDate to Date.now. As next year the age will change!

IF you just asking for a Int then when they entered the number, do a check that it a validate range. You can then use an alert tp tell user of the range.

2      

Well, I used the age as an example, but I'm actually working with a Double instead of an Int.

Anyways, a Picker is also a good idea.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.