UITextField如何禁用粘贴?
问问题
16748 次
1 回答
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;
}
还要检查这个链接
已编辑
在 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
}
于 2013-04-01T15:20:59.967 回答