UITextField如何禁用粘贴?

时间:2013-04-01 14:58:56

标签: ios objective-c uitextfield

UITextField如何禁用粘贴?

1 个答案:

答案 0 :(得分:76)

覆盖canPerformAction:withSender:方法,以便为您不希望允许的操作返回NO

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
    {
        if (action == @selector(paste:))
            return NO;
        if (action == @selector(select:))   
            return NO;   
        if (action == @selector(selectAll:))   
            return NO;  
        return [super canPerformAction:action withSender:sender];
    }

在上面的代码中,您只需为粘贴

编写

另一种方式

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    UIMenuController *menuController = [UIMenuController sharedMenuController];
    if (menuController) {
        [UIMenuController sharedMenuController].menuVisible = NO;
    }
    return NO;
}

同时检查This link

已编辑

在iOS 7中,你可以这样做,

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [[UIMenuController sharedMenuController] setMenuVisible:NO animated:NO];
    }];
    return [super canPerformAction:action withSender:sender];
}

对于Swift用户

override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    if action == #selector(copy(_:)) || action == #selector(paste(_:)) {
        return false
    }

    return true
}

如果您想在TEXTFIELD上打开日期选择器或选择器视图,请单击下面的代码工作。

在您的课程中添加以下两种方法。

//Hide Menu View
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {

    if YOURTEXTFIELD.isFirstResponder {
        DispatchQueue.main.async(execute: {
            (sender as? UIMenuController)?.setMenuVisible(false, animated: false)
        })
        return false
    }

    return super.canPerformAction(action, withSender: sender)
}

//必须实施

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
            return false
}