使用IQKeyboardManager关闭键盘以及触发按钮的touchupinside事件

时间:2017-09-14 10:59:05

标签: ios swift iqkeyboardmanager

我在appdelegate中使用此代码

IQKeyboardManager.sharedManager().enable = true
IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true
IQKeyboardManager.sharedManager().touchResignedGestureIgnoreClasses = [UINavigationBar.self,UIControl.self]

分配 touchResignedGestureIgnoreClasses 属性允许我在键盘打开时触发UIButton事件,但它不会同时解除键盘。

2 个答案:

答案 0 :(得分:0)

尝试在处理按钮事件的函数中添加这行代码:

self.view.endEditing = true

答案 1 :(得分:0)

在这种特定情况下,您可能需要创建自己的按钮类子类 UIButton 并观察其中的事件。稍后再将UIButtons自定义类指定为您自己创建的按钮。

class KOButton: UIButton {

    var isKeyBoardOpened = false

    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code

        self.addObserver(self, forKeyPath: "highlighted", options: .new, context: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardOpened), name: Notification.Name.UIKeyboardDidShow, object: nil)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "highlighted" {
            UIApplication.shared.keyWindow?.endEditing(true)
            self.isKeyBoardOpened = false
        }
    }

    func keyboardOpened() {
        isKeyBoardOpened = true;
    }


}

Storyboard changes

我希望这可能会对你有所帮助,如果它不起作用,请遵循下面提到的另一种方法

UIViewController

撰写扩展程序
// Declare a global var to produce a unique address as the assoc object handle
private var AssociatedObjectHandle: UInt8 = 0
extension UIViewController{

    var isKeyBoardOpened: Bool {
        get {
            return objc_getAssociatedObject(self, &AssociatedObjectHandle) as! Bool
        }
        set {
            objc_setAssociatedObject(self, &AssociatedObjectHandle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }


    func addKBOforButton(aButton: UIButton) {
        aButton.addObserver(self, forKeyPath: "highlighted", options: .new, context: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardOpened), name: Notification.Name.UIKeyboardDidShow, object: nil)
    }

    override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "highlighted" {
            UIApplication.shared.keyWindow?.endEditing(true)
            self.isKeyBoardOpened = false
        }
    }

    func keyboardOpened() {
        isKeyBoardOpened = true;
    }
}

然后从viewcontroller中调用此函数

self.addKBOForButton(aButton: button)