当UITextfield为空时,禁用所有UIResponderStandardEditActions

时间:2018-11-20 09:41:54

标签: ios swift uitextfield uiresponder

我目前正在尝试阻止schemas为空时显示所有UIResponderStandardEditActions,例如copypastedelete。如果用户输入了消息,我只想显示给他们。我已经尝试了2种解决方案,但目前无法正常工作,我不确定是否与UITextfield或。我在iOS 12 overriding中尝试了canPerformAction UITextfield方法,并使用了后来在extension中分配给UITextfield的自定义类,但是没运气。还有另一种方法可以做到这一点。这是我尝试过的。

Storyboard

1 个答案:

答案 0 :(得分:0)

只需重写您的子类,然后使用此类代替UITextField。顺便说一句,这将禁用整个条件下的复制粘贴,剪切,因此您需要向开关盒中添加一些hasText: Bool或相关条件。

@IBDesignable
class ActionsDisabledUITextField: UITextField {

    @IBInspectable var isPasteEnabled: Bool = false

    @IBInspectable var isSelectEnabled: Bool = false

    @IBInspectable var isSelectAllEnabled: Bool = false

    @IBInspectable var isCopyEnabled: Bool = false

    @IBInspectable var isCutEnabled: Bool = false

    @IBInspectable var isDeleteEnabled: Bool = false

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        switch action {
        case #selector(UIResponderStandardEditActions.paste(_:)) where !isPasteEnabled,
             #selector(UIResponderStandardEditActions.select(_:)) where !isSelectEnabled,
             #selector(UIResponderStandardEditActions.selectAll(_:)) where !isSelectAllEnabled,
             #selector(UIResponderStandardEditActions.copy(_:)) where !isCopyEnabled,
             #selector(UIResponderStandardEditActions.cut(_:)) where !isCutEnabled,
             #selector(UIResponderStandardEditActions.delete(_:)) where !isDeleteEnabled:
            return false
        default:
            //return true : this is not correct
            return super.canPerformAction(action, withSender: sender)
        }
    }
}