Swift 3 - 向UINavigationController子类添加导航项

时间:2017-04-13 04:24:38

标签: ios swift swift3

我有一个名为UINavigationController的{​​{1}}子类。我将其子类化的原因是因为我以编程方式构建UI,对于这个特定的导航类,我需要在其navigationBar的左/右部分有一个特定的按钮。

这就是我在子类中的含义:

NavController

import UIKit class NavController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.navigationBar.alpha = 1.0 self.navigationBar.barTintColor = UIColor.navi self.navigationBar.isTranslucent = false self.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] // tearing my hair out here let refresh = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.refresh, target: self, action: #selector(doSomething)) self.navigationItem.leftBarButtonItem = refresh } func doSomething() { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } 访问navigationItem.leftBarButtonItem是否正确? 我的头发用完了。

提前致谢。

3 个答案:

答案 0 :(得分:2)

快速回复:没有。

navigationItem.leftBarButtonItem是UINavigationController中视图控制器的属性,而不是导航控制器本身。

e.g:

let firstVC = UIViewController()
let firstBarItem = UIBarButtonItem()
firstVC.navigationItem.rightBarButtonItem = firstBarItem
let nc = UINavigationController(rootViewController: firstVC)

导航控制器现在显示firstBarItem

let secondVC = UIViewController()
let secondBarItem = UIBarButtonItem()
secondVC.navigationItem.rightBarButtonItem = secondBarItem

nc.pushViewController(secondVC, animated: true)

导航控制器现在显示secondBarItem

如果您回到firstVC,它会自动显示firstBarItem

答案 1 :(得分:0)

是否要在导航栏中显示refresh按钮?但是目前的代码不能这样做,对吧?让我们使用这段代码:

if let navigationItem = navigationBar.items?.first {
    navigationItem.leftBarButtonItem = refresh
}

答案 2 :(得分:0)

// Below Code is for Left Side UIBarButtonItem for Navigation Bar
let leftItemBarButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(leftBarButtonTapped))

self.navigationItem.leftBarButtonItem = leftItemBarButton

func leftBarButtonTapped() {
print("Left Bar Button Item")
}

// Below Code is for Right Side UIBarButtonItem for Navigation Bar

let rightItemBarButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(rightBarButtonTapped))

self.navigationItem.rightBarButtonItem = rightItemBarButton

func rightBarButtonTapped() {
print("Right Bar Button Item")
}

如果要使用UIBarButtonItem方法将图像放入导航栏,还有不同的方法