Make the navigationbar title clickable swift

2019-03-09 21:07发布

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

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-09 21:22

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
}
查看更多
祖国的老花朵
3楼-- · 2019-03-09 21:34

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
查看更多
何必那么认真
4楼-- · 2019-03-09 21:35

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() {
}
查看更多
登录 后发表回答