【问题标题】:Disable all UIResponderStandardEditActions when UITextfield is empty当 UITextfield 为空时禁用所有 UIResponderStandardEditActions
【发布时间】:2019-04-22 17:27:10
【问题描述】:

我目前正试图阻止所有UIResponderStandardEditActions(如copypastedelete)在UITextfield 为空时出现。我只想在用户输入消息时向他们展示。我已经尝试了 2 种解决方案,但目前不起作用,我不确定它是否与 iOS 12 或有关。我在UITextfield extension 中尝试了overridingcanPerformAction 方法,并在Storyboard 中使用了后来分配给UITextfield 的自定义类,但没有运气。有没有另一种方法可以做到这一点。这是我尝试过的。

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
    }
}

【问题讨论】:

    标签: ios swift uitextfield uiresponder


    【解决方案1】:

    只需用您的子类覆盖并使用此类而不是 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)
            }
        }
    }
    

    【讨论】:

    • 什么不起作用?我在我的多个项目中使用这个类。你是如何实施的?你能分享一些细节吗?
    猜你喜欢
    • 2011-06-02
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 2020-02-18
    • 2022-06-12
    • 2016-06-10
    相关资源
    最近更新 更多