防止uitextfield粘贴非数字字符串

时间:2018-07-17 11:23:25

标签: ios swift uitextfield paste uipasteboard

我正在使用带有电话号码的文本字段。 复制粘贴在文本字段中启用。 文本字段不应采用非数字值。

但是问题是,如果粘贴任何字符串,我将采用非数字值。

我尝试了以下代码,但没有成功:

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{

    if (action == @selector(paste:))
    {
        UIPasteboard *pasteboard =[UIPasteboard generalPasteboard];
        NSLog(@"%@",pasteboard.string);
        if ([self isAllDigits:pasteboard.string]) {
        return YES;
        }
        return NO;

    }
    return [super canPerformAction:action withSender:sender];
}

3 个答案:

答案 0 :(得分:0)

类似这样的东西:

- (BOOL)numeric:(NSString *)aString {
    NSScanner *scanner = [NSScanner scannerWithString: aString];
    if ([scanner scanFloat:NULL]) {
        return [scanner isAtEnd];
    }
    return NO;
}

答案 1 :(得分:0)

下面是使用UITextfield的自定义类来执行此操作的示例,但是在Swift;)中,只需创建一个新的swift文件并将其粘贴即可。将您的文本归档类名称更改为“ MyTextfield”(根据需要更改类名称)。 PFA 以在属性窗口中查看情节提要视图。

enter image description here

import UIKit

@IBDesignable

class MyTextField: UITextField {

@IBInspectable var isPasteEnabled: Bool = true

@IBInspectable var isCopyEnabled: Bool = true

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    switch action {
    case #selector(UIResponderStandardEditActions.paste(_:)) where !isPasteEnabled,
         #selector(UIResponderStandardEditActions.copy(_:)) where !isCopyEnabled:
        return false
    default:
        return super.canPerformAction(action, withSender: sender)
    }
  }
}

答案 2 :(得分:0)

最后通过将下面的代码放在UITextfield子类中来解决。

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if ((self.keyboardType = UIKeyboardTypePhonePad))
    {
        if (action == @selector(paste:))
        {
            UIPasteboard *pasteboard =[UIPasteboard generalPasteboard];
            NSLog(@"%@",pasteboard.string);
            if ([self isAllDigits:pasteboard.string]) {
                return YES;
            }
            return NO;

        }
    }
    return [super canPerformAction:action withSender:sender];
    //prevent uitextfield to paste non numeric string
}
- (BOOL) isAllDigits:(NSString *)testString
{
    NSCharacterSet* nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    NSRange r = [testString rangeOfCharacterFromSet: nonNumbers];
    return r.location == NSNotFound;
}