Make the navigationbar title clickable swift

帅比萌擦擦* 提交于 2019-12-31 09:32:14

问题


I would like to make the navigationbar title to be clickable. When user click on it, it should perform a segue. But I have no idea how to do this.

I have tried the following to get the title and apply the Tap gesture to it.

var subviews  = self.navigationController?.navigationBar.subviews
        if let subviews = subviews {
            // Better check for array length before accessing to the 1st element
            var subview = subviews [0]
        }

but its giving me error Variable subview inferred to have type AvyObject, which may be unexpected


回答1:


One more approach to add button as a title of navigation controller.

You need to set navigation item title view to your button object

Create button object in viewDidLoad() method:

Swift 4.0 Edit

let button =  UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
button.backgroundColor = .red
button.setTitle("Button", for: .normal)
button.addTarget(self, action: #selector(clickOnButton), for: .touchUpInside)
navigationItem.titleView = button

Here you can see in last line button is directly set to the titleView of navigationItem which will add button at the center of navigation bar.

Action method for button is below:

@objc func clickOnButton() {
}



回答2:


Kampai's answer updated for Swift 3:

let button =  UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
button.setTitle("Button", for: .normal)
button.addTarget(self, action: #selector(self.clickOnButton), for: .touchUpInside)
self.navigationItem.titleView = button



回答3:


To get rid of that error, specify a type for your if let constant. I'd also recommend changing that if let constant name since it's the same as the one already declared in the previous line.

var subviews  = self.navigationController?.navigationBar.subviews
if let subviewArray:NSArray = subviews {
     // Better check for array length before accessing to the 1st element
     var subview:UILabel = subviewArray[0] // <-- If the subview's a UILabel
}


来源:https://stackoverflow.com/questions/27632820/make-the-navigationbar-title-clickable-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!