使导航栏标题可以快速点击
我想使navigationbar
栏标题可以点击。 当用户点击它时,它应该执行segue。 但我不知道该怎么做。
我尝试了以下内容来获取标题并将Tap手势应用于它。
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] }
但它给我的错误Variable subview inferred to have type AvyObject, which may be unexpected
另一种添加按钮作为导航控制器标题的方法。
您需要将导航项标题视图设置为按钮对象
在viewDidLoad()
方法中创建按钮对象:
Swift 3.0编辑
let button = UIButton(type: .custom) button.frame = CGRect(x: 0, y: 0, width: 100, height: 40) button.backgroundColor = UIColor.red button.setTitle("Button", for: .normal) button.addTarget(self, action: #selector(self.clickOnButton), for: .touchUpInside) self.navigationItem.titleView = button
在这里你可以看到在最后一行按钮被直接设置为navigationItem
的titleView
,它将在导航栏的中心添加按钮。
按钮的动作方法如下:
func clickOnButton(button: UIButton) { }
Kampai的答案更新为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
要消除该错误,请为if let
常量指定一个类型。 我还建议改变它, if let
常量名称,因为它与前一行中已经声明的那个相同。
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 }