Swift 3.0向导航栏添加右键 [英] Swift 3.0 Adding a Right Button to Navigation Bar

查看:106
本文介绍了Swift 3.0向导航栏添加右键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在视图控制器的顶部添加了一个导航栏。我试图根据条件控制按钮是否可见,但是我在添加按钮时遇到问题。到目前为止,我有,

I have added a navigation bar to the top of a view controller. I am trying to control whether a button is visible based a condition, but I am having trouble adding the button. So far I have,

var addButton: UIBarButtonItem = UIBarButtonItem(title: "test", style: .done, target: self, action: #selector(addTapped))

override func viewDidLoad() {
    super.viewDidLoad()

    let boool = true
    if boool {
        self.navigationItem.rightBarButtonItem = self.addButton
    }
    else {
        self.navigationItem.rightBarButtonItem = nil
    }
}

func addTapped(sender: AnyObject) {
    print("hjxdbsdhjbv")
}

我认为它没有正常工作,因为我已经在VC中添加了导航栏,而不是使用导航控制器并在那里使用栏。我想知道是否有办法使用此导航栏。

I believe it is not working properly because I have added a navigation bar into the VC, instead of using a navigation controller and working with the bar there. I was wondering if there was a way to work with this navigation bar.

推荐答案

你说你通过故事板向视图控制器添加了 UINavigationBar ,但查看您提供的代码,IB中的导航栏没有插座连接。

You say you added a UINavigationBar to your view controller via storyboard, but looking at the code you provided there is no outlet connection to your navigation bar in IB.

要访问 self.navigationItem ,您的视图控制器必须嵌入 UINavigationController 或成为层次结构的一部分。除非您需要在单个视图控制器上使用自定义导航栏,否则我建议从Interface Builder中删除它,然后确保所讨论的视图控制器嵌入在 UINavigationController 或者它被从嵌入在导航控制器中的另一个控制器推入导航堆栈,然后你应该看到你的 UIBarButtonItem

In order to access self.navigationItem your view controller must be embedded in a UINavigationController or be part of a hierarchy which is. Unless you have a need for a custom navigation bar on an individual view controller, I suggest removing that from Interface Builder, then making sure either the view controller in question is embedded in a UINavigationController or it is being pushed onto the navigation stack from another controller which is embedded in a navigation controller and then you should see your UIBarButtonItem.

这篇关于Swift 3.0向导航栏添加右键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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