开发者

Check if a string contains letters and cancel them

I've got an UITextField and I need to allow only numbers, comma or point typing in this field.

How can I check if this string contains any character instead of these above and how can I replace/delete them?

My field will store a cost and I need only numbers, comma or point...

Can anyone help me开发者_如何转开发?

Thanks!


For the textfield, you could use the UITextFieldDelegate and implement the textField:shouldChangeCharactersInRange:replacementString: method. According to the docs, "the text field calls this method whenever the user types a new character in the text field or deletes an existing character." In the method, you should do a check for all non-number characters and remove them.


You can use the -textFieldDidEndEditing: method from the UITextFieldDelegate protocol. This method is called whenever a text field resigns the first responder status (i.e. ends editing). This is the chance to check the entered String. If you want to perform a check after each character that has been input, use -textField:shouldChangeCharactersInRange:replacementString: as donkim suggests.


Instead to check the string why cant you assign the keyboard value of the textfield as NumberPad. So that the user will not be able to type a string.


You can do it by monitoring user input in the field and automatically removing non-matching characters. Create an IBAction method:

- (IBAction)validateEntry:(id)sender;

then attach it to the text field's Editing Changed event. The method will be called every time the text in the field changes, whether from the user typing or from the user pasting text in.

Inside the method you can examine the text and remove offending characters or, more politely, update a UILabel that tells the user they've entered invalid characters and disable any submit buttons until it's fixed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜