In such specific cases you might required to create your own button class sub-classing UIButton and observe the events inside it. Later then specify UIButtons custom class as your own button which you have created.
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;
}
}

I hope this might helps you, if it did't work the follow the another approach below mentioned
Write an extension for 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;
}
}
And then call this function from your viewcontroller
self.addKBOForButton(aButton: button)