使导航栏标题可以快速点击 [英] Make the navigationbar title clickable swift

查看:210
本文介绍了使导航栏标题可以快速点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将导航栏标题设为可点击。当用户点击它时,它应该执行segue。但是我不知道该怎么做。

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.

我已经尝试了以下方法来获取标题并将Tap手势应用到它。

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]
        }

但是它给我的错误变量子视图推断为具有类型AvyObject,这可能是意外的

推荐答案

另一种添加按钮作为导航控制器标题的方法。

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

您需要将导航项标题视图设置为按钮对象

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

中创建按钮对象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

在这里你可以看到在最后一行按钮直接设置为 titleView navigationItem ,这将在导航栏的中心添加按钮。

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.

按钮的操作方法如下:

func clickOnButton(button: UIButton) {
}

这篇关于使导航栏标题可以快速点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆