使用UIBarButtonItem,點(diǎn)擊事件無法觸發(fā)。
原因是點(diǎn)擊事件被UIGestureRecognizer 所覆蓋,點(diǎn)擊事件無法傳遞下去。
兩種解決方式。
第一種:
設(shè)置cancelsTouchesInView屬性。
cancelsTouchesInView默認(rèn)為true,當(dāng)屬性為true時會只響應(yīng)touch事件,該觸摸也就不會繼續(xù)在事件傳遞鏈傳遞下去。當(dāng)設(shè)置為false時則不會終止事件傳遞,touch事件和點(diǎn)擊事件都會觸發(fā)。
let tapGestureRecognizer = UITapGestureRecognizer(target: self,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? action: #selector(handleTapGesture))
tapGestureRecognizer.cancelsTouchesInView = false
self.view.addGestureRecognizer(tapGestureRecognizer)
//單擊手勢響應(yīng)
? ? @objc func handleTapGesture() {
? ? print("測試")
? ? ? ?}
第二種:
手動生成按鈕,指定點(diǎn)擊方法
var navigationBar:UINavigationBar?
var titleTxt = "我的設(shè)備"
override func viewDidLoad() {
? ? ? ? super.viewDidLoad()
? ? ? ? self.navigationController?.isNavigationBarHidden=true
? ? ? ? //實例化導(dǎo)航條
? ? ? ? navigationBar = UINavigationBar(frame: CGRect(x:0, y:20, ? ????????width:self.view.frame.size.width, height:60))
? ? ? ? self.view.addSubview(navigationBar!)
? ? ? ? navigationBar?.pushItem(navItem(), animated: false)
? ? ? ? // Do any additional setup after loading the view.
? ? }
@objc func navItem() -> UINavigationItem{
? ? ? ? // 創(chuàng)建導(dǎo)航欄組件
? ? ? ? let navItem = UINavigationItem()
? ? ? ? //生成按鈕,事件設(shè)置為點(diǎn)擊后觸發(fā)
? ? ? ? let rightButton = UIButton(type: UIButtonType.custom)
? ? ? ? rightButton.frame = CGRect(x: 0, y: 0, width: 33, height: 32)
? ? ? ? rightButton.addTarget(self, action: #selector(test_clicked(_:)), for: UIControlEvents.touchUpInside)
? ? ? ? let rightItem = UIBarButtonItem(customView: rightButton)
? ? ? ? // 自定義導(dǎo)航欄的title,用UILabel實現(xiàn)
? ? ? ? let titleLabel = UILabel(frame: CGRect(x:0,y:0,width:50,height:60))
? ? ? ?titleLabel.text = titleTxt
? ? ? ? // 設(shè)置自定義的title
? ? ? ? navItem.titleView = titleLabel
? ? ? ? navItem.setRightBarButton(rightItem, animated: true)
? ? ? ? return navItem
?? ?}
@objc func test_clicked(_ sender: AnyObject) {
????print("測試")
}