0

I am currently trying to prevent all UIResponderStandardEditActions like copy, paste, delete from showing up when the UITextfield is empty. I would only like to show them if the user has types a message. I have tried 2 solutions and currently don't work, I'm not sure if its to do with iOS 12 or. I have tried overriding the canPerformAction method both in a UITextfield extension and using a custom class later assigned to the UITextfield in the Storyboard but no luck. Is there another way to do this. Here is what I have tried.

extension UITextField {
    open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
            if self.text!.isEmpty {
                return false
            }

            return action == #selector(UIResponderStandardEditActions.paste(_:))
        }
}

class CustomTextField: UITextField {
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(UIResponderStandardEditActions.paste(_:)) || action == #selector(UIResponderStandardEditActions.copy(_:)) || action == #selector(UIResponderStandardEditActions.delete(_:)) {
            return false
        }
        return true
    }
}
mandem112
  • 181
  • 14

1 Answers1

0

Just override with your subclass and use this class instead of UITextField. By the way, this will disable copy paste,cut for whole conditions so that you need to add some hasText: Bool or related condition to the switch case.

@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)
        }
    }
}
Emre Önder
  • 2,408
  • 2
  • 23
  • 73
  • What is not working? I'm using this class in my more than one project. How did you implement it? Can you please share some detail? – Emre Önder Nov 20 '18 at 11:32