Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make the navigationbar title clickable swift

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

like image 609
Atif Farrukh Avatar asked Dec 24 '14 06:12

Atif Farrukh


2 Answers

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() {
}
like image 147
Kampai Avatar answered Nov 02 '22 10:11

Kampai


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
like image 34
hashemi Avatar answered Nov 02 '22 11:11

hashemi