I'm working on swift/xcode and I want to check if the input in the text fields are valid. I have a total of 5 text fields, each taking a number of length 2. How do I do that?
(edit: Converting text field to double had typo..)
I'm working on swift/xcode and I want to check if the input in the text fields are valid. I have a total of 5 text fields, each taking a number of length 2. How do I do that?
(edit: Converting text field to double had typo..)
I think you want to reference the string you created, rather than declaring a new variable.
Try this
let val1String = course1.text
let val1 = NSString(string: val1String).doubleValue
The parameter to NSString is looking for a String. You made a string in the prior line, so use that one.
also, note:
let s = "123"
print ("\(NSString(string: s).doubleValue)")
\\ prints 123.0
let s2 = "abc"
print ("\(NSString(string: s2).doubleValue)")
\\ prints 0.0
See this: Swift - How to convert String to Double
if let cost = Double(textField.text!) {
print("The user entered a value price of \(cost)")
} else {
print("Not a valid number: \(textField.text!)")
}
Then just make sure that cost
is in the range 0...99 or 0..<100
When it comes to restricting textField
input to only take numbers, please refer to this answer here, it will help you: https://stackoverflow.com/a/31812151/12278515.
What you are looking for in the textField
setup is this, but please read the whole linked answer as to get an understanding of how UITextField
's delegates work
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return Double(string) != nil
}
You can check the count of textField
characters by using the following: textField.text.count
.
So the condition you are looking for something is along the lines of:
if textField.text.count != 2 {
// Here comes the action, if the textFied lenght is not 2 characters
}
Hope this helps