开发者

Restricting copy paste of string in numeric textfield

I have a textbox in which I wanted a user to enter only numbers. I hav开发者_开发百科e 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?


@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.


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:

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜