我敢肯定,這是非常容易的,但我無法得到一個簡單的例子,用UIInputViewController工作。我有兩個按鈕,它們出現,但敲擊它們沒有效果。在谷歌搜索中,我發現了幾個完全如此的問題 - 沒有答案!我觀看了關於這個主題的WWDC 2017視頻,但是他們對這一點有所掩蓋,並且他們的代碼有效,但我不明白爲什麼我的代碼不會。UIInputViewController(自定義鍵盤) - UIButton操作未被觸發 - 爲什麼,爲什麼?
代碼(只是概念驗證)在下面,任何幫助將非常感激。
邁克爾
class ViewController: UIViewController {
@IBOutlet weak var testTF: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
testTF.inputView = CustomView(nibName:nil,bundle:nil).inputView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
class MyButton:UIButton {
init(frame: CGRect, title:String) {
super.init(frame: frame)
backgroundColor = UIColor.lightGray
isUserInteractionEnabled = true
setTitle(title, for: .normal)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CustomView: UIInputViewController {
override init(nibName:String?, bundle:Bundle?) {
super.init(nibName:nibName, bundle:bundle)
let keyboard:UIView = UIView(frame: CGRect(x:0.0,y:0.0,width:768.0, height:240.0))
keyboard.backgroundColor = UIColor.red
let zeroKey:MyButton = MyButton(frame: CGRect(x:0.0,y:0.0,width:45.0,height:50.0), title:"0")
zeroKey.addTarget(self, action: #selector(clickMe(sender:)), for: .allEvents)
keyboard.addSubview(zeroKey)
let oneKey:UIButton = MyButton(frame: CGRect(x:50.0,y:0.0,width:45.0,height:50.0), title:"1")
oneKey.addTarget(self, action: #selector(clickMe(sender:)), for: .allEvents)
keyboard.addSubview(oneKey)
self.inputView?.backgroundColor = UIColor.blue
self.inputView?.frame = CGRect(x:0.0,y:0.0,width:UIScreen.main.bounds.width, height:240.0)
self.inputView?.isUserInteractionEnabled = true
self.inputView?.addSubview(keyboard)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func clickMe(sender:Any) {
print("hey, why am I not being called?")
}
}
keyboard.bringSubViewToFront:(一鍵)嘗試這樣做後,鍵盤加入inputview。 –
這沒有奏效,但謝謝你的建議。 –
我調整了這一段時間,試圖與一個.system UIButton一起工作,而且工作。然後我回到我的MyButton類,這也工作。最後,我粘貼了上面的代碼,清理了該項目,並且它仍然可以工作。看起來像模擬器的錯誤,也許?無論如何,這是一件有趣的事情。這是什麼協議?刪除整個問題,或將其作爲警告留給別人? –