Reputation: 38142
I have a textbox in which I wanted a user to enter only numbers. I have implemented the number keypad there. But if someone puts my app in the background and copies some character string from some other app and comes back to my app and pastes it, it successfully pastes the string content into my numeric textfield. How can I restrict this scenario?
Upvotes: 3
Views: 1821
Reputation: 299265
@theChrisKent is close, but there's a slightly better way. Use the delegate method -textView:shouldChangeTextInRange:replacementText:
. Check if replacementText
contains any non-numbers, and if so return NO
.
Upvotes: 7
Reputation: 15099
You can disable pasting altogether by following the top answer on this question: How disable Copy, Cut, Select, Select All in UITextView
Just subclass the UITextView
and override this method (code stolen from above question):
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(paste:)
return NO;
return [super canPerformAction:action withSender:sender];
}
Otherwise you can implement the UITextViewDelegate
protocol and implement the textViewDidChange:
method and check if it's numeric. If not, undo the changes. Documentation here: http://developer.apple.com/library/ios/documentation/uikit/reference/UITextViewDelegate_Protocol/Reference/UITextViewDelegate.html#//apple_ref/occ/intfm/UITextViewDelegate/textViewDidChange:
Upvotes: 0