Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialNicholas Kennedy
14,015 PointsAllow only one decimal in UITextField Class?
I'm a beginner working on my own practice app. Trying to create a text field that only allows for one decimal place in a field where users are asked to input a price. Each time the function is accessed through my view controller the decimal counter remains at one and doesn't increment. the field will continue to accept decimal characters and the console repeatedly prints 1. Any insight would be greatly appreciated. (or likely there is a better solution that I am totally missing?)
import UIKit
import Foundation
class NumberValidator: UITextField {
//MARK: Glabal Variables
var decimalCounter = 0
//MARK: Validate as numeric allowing decimal
func validatePriceField(string: String) -> Bool {
if ( string == "." && decimalCounter < 1 ) {
decimalCounter++
print("\(decimalCounter)")
}
if ( string == "." && decimalCounter >= 1 ) {
return false
}
switch string {
case "0","1","2","3","4","5","6","7","8","9":
return true
case ".":
return true
default:
let array = Array(string.characters)
if array.count == 0 {
return true
}
return false
}
}
Nicholas Kennedy
14,015 PointsThanks for the reply Jhoan,
purpose is for the user to be able to enter $5 or $25.7 or $6.50 but inhibit them from entering $6.A.6 or $5!... or $91.777 etc, I have in multiple classes in an attempt to conform to best practices as there are multiple text fields in the main view controller, does that clarify ?...
1 Answer
Michael Reining
10,101 PointsI would keep track of the user input via
UITextFieldTextDidChangeNotification
Keep track of the string users have entered along the way and then prevent them from entering something you do not like.
I hope that helps,
Mike
PS: Thanks to the awesome resources on Team Treehouse, I just launched my first app.
Jhoan Arango
14,575 PointsHey Mike, amazing app..
I'm sure that app will be a hit!!!
Jhoan Arango
14,575 PointsJhoan Arango
14,575 PointsI may be able to help, but don't understand the purpose. Perhaps going into a bit more details I may chip in on something.