Swift 3.0向导航栏添加右键

时间:2017-07-13 00:14:16

标签: ios swift button navigationbar

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

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中添加了导航栏,而不是使用导航控制器并在那里使用栏。我想知道是否有办法使用此导航栏。

6 个答案:

答案 0 :(得分:38)

这很简单。将这行代码放到viewDidLoad

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

答案 1 :(得分:6)

let rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "EditImage"), style: .done, target: self, action: #selector(ViewController.call_Method))

self.navigationItem.rightBarButtonItem = rightBarButtonItem

答案 2 :(得分:4)

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

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

答案 3 :(得分:1)

首先,您需要将导航栏连接到IBOutlet,以便在代码中引用它。之后,此代码应该起作用:

    let navigationItem = UINavigationItem(title: "Title")
    navigationItem.rightBarButtonItem = self.addButton
    navigationItem.hidesBackButton = true
    self.navigationBar.pushItem(navigationItem, animated: false)

答案 4 :(得分:0)

迅速4.2;

添加viewController

override func viewDidLoad() {
        super.viewDidLoad()
        self.addNavigationBarButton(imageName: "ic_back", direction:.left)
 }

添加Class您的API或实用程序类

public func addNavigationBarButton(imageName:String,direction:direction){
    var image = UIImage(named: imageName)
    image = image?.withRenderingMode(.alwaysOriginal)
    switch direction {
    case .left:
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: #selector(goBack))
    case .right:
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: #selector(goBack))
    }
}

@objc public func goBack() {
    self.navigationController?.popViewController(animated: true)
}

public enum direction {
    case right
    case left
}

答案 5 :(得分:0)

在Xcode 10.2中进行了测试,速度为5.0; 首先,我已经将ViewController嵌入到IB的UINavigationController中。 然后在ViewDidLoad中包含这些行

self.title = "orange"
 self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(changeLayout)).

注意-访问标题或通过导航控制器添加按钮无效。例如:设置标题-Self.navigationcontroller.navigationItem.title无效,