iOS 11无法禁用UITextField的复制粘贴选项

3

我正在使用Xcode 9和iOS 11,搜索了如何禁用复制粘贴选项,但没有成功。

enter image description here

以下是我尝试的内容:
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    if action == #selector(UIResponderStandardEditActions.paste(_:)) || action == #selector(UIResponderStandardEditActions.copy(_:)) {
        return false
    }

    return true
}

并且也尝试了:

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(UIResponderStandardEditActions.paste(_:)) || action == #selector(paste(_:)) || action == #selector(cut(_:)) || action == #selector(selectAll(_:)) || action == #selector(select(_:)){
            return false
        }

        return true
    }

我尝试了很多来自Stackoverflow的代码,但都没有成功。事实上,我不想在长按UITextField时显示上面的菜单。

1
那个方法被调用了吗? - Nikhil Manapure
我检查了你的代码,它在iOS 11上运行正常。 - RajeshKumar R
@NikhilManapure - 是的 - Govaadiyo
@Rajesh - 你没看到上面的选择菜单吗?它是作为图像放置的。 - Govaadiyo
我看到了菜单,但是粘贴、复制、全选、选择和剪切等选项在菜单中不可用。 - RajeshKumar R
显示剩余3条评论
3个回答

4

已在iOS 12中进行测试并运作正常:

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool
{
    if  action == #selector(self.paste(_:))
        ||
        action == #selector(self.copy(_:))
        ||
        action == #selector(self.cut(_:))
        ||
        action == #selector(self.select(_:))
        ||
        action == #selector(self.selectAll(_:))

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

3

以下Swift 5代码适用于我

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    OperationQueue.main.addOperation {
        UIMenuController.shared.setMenuVisible(false, animated: false)
    }
    return super.canPerformAction(action, withSender: sender)
}

0

复制并粘贴这个UITextView子类

public class NoEditMenuTextView: UITextView {
        override init(frame: CGRect, textContainer: NSTextContainer?) {
            super.init(frame: frame, textContainer: textContainer)
            OperationQueue.main.addOperation {
                UIMenuController.shared.hideMenu()
            }
        }
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
        
        open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
            return false
        }
    }

然后,将您的文本视图或文本字段设置为 NoEditMenuTextView 而不是 UITextView。

@IBOutlet var myTextView: NoEditMenuTextView!

注意:如果你在storyboards中创建了你的textview,那么你还需要在检查器窗口中更改类别。(见照片)enter image description here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接