swift 實機(jī)測試時導(dǎo)航欄按鈕失效

使用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("測試")

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容