在這種特定的情況下,您可能需要創建自己的按鈕類子類的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;
}
}
我希望這力量可以幫助你,如果我以前不工作請按照下面的另一種方法中提到
寫出擴展的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;
}
}
然後從您的視圖控制器調用此功能
self.addKBOForButton(aButton: button)
IQKeyboardManager不會取消鍵盤,如果你是通過包括在** touchResignedGestureIgnoreClasses控制執行任何操作**,所以,你已經包括您的UIButton –
@Jayachandra一個我應該怎麼做然後..如果我跳過從這個屬性的UIbutton,它只是駁回鍵盤的事件不會被解僱 –