Reputation: 1
Hi I'm creating a iphone app and one of the conditions is that the user should not be able to enter “0” as the first digit of his/her response (when the UITextField as its placeholder value) unless the correct answer is 0.
What I have so far is but it lets me enter a 0 still but doesn't let 100 which should happen
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let leadingZero = textField.text?.rangeOfString("0")
let replacementZero = string.rangeOfString("0")
if leadingZero != nil && replacementZero != nil {
return false
}
return true
}
Upvotes: 0
Views: 216
Reputation: 4815
// Create Textfield action method Editing Changed
@IBAction func TextfieldCheck(sender: AnyObject) {
if YOURTEXTFIELD.text?.characters.count > 0 {
let str : String = YOURTEXTFIELD.text!
if str.characters.count < 3 {
if str .containsString("0")
{
YOURTEXTFIELD.text = ""
}
}
}
}
Your problem will be solve now . If any problem face with my this code then tell me
Upvotes: 0
Reputation: 14571
Take a correctAnswer variable
//make it true or false depending whether your correct answer is zero
var correctAnswerIsZero = false
Add a target to the textfield
myTextField.addTarget(self, action: #selector(textfieldDidChange), for: .editingChanged)
Defination of target
func textfieldDidChange(textfield:UITextField) {
if correctAnswerIsZero {
} else {
//if correct answer is not zero
if textfield.text?.characters.first == "0" {
print("You have entered 0, so deleting it")
textfield.text = ""
}
}
}
Upvotes: 1
Reputation: 3235
If you only need to check whether the textField is empty, and refuse to allow a 0 to be entered if it is, you can do the following:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return (textField.hasText || string != "0") ? true : false
}
hasText ignores placeholder text, so that won't be an issue.
Upvotes: 0