如何更改UINavigationController标题& backButton编程?

时间:2017-03-06 07:17:44

标签: ios iphone swift uinavigationcontroller

我有两个viewControllers。

vc1 - > presentVC - > vc2

vc2继承UINavigationController

我想设置标题& backcutton在vc2中,但它不起作用。

class vc2: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()

    // set title!!!
    //self.navigationItem.title = "123"
    //self.navigationController?.navigationBar.topItem?.title = "123"
    //self.title = "123"
    //self.navigationBar.topItem?.title = "123"
    //self.navigationItem.title = "123"

    // set backButton!!!
    let navButtonWidth:CGFloat = 44
    let backButton:UIButton = UIButton()
    backButton.setImage(backImage, for: .normal)
    backButton.addTarget(self, action: #selector(back), for: .touchUpInside)
    self.navigationItem.leftBarButtonItems = [UIBarButtonItem(customView: backButton)]

}

2 个答案:

答案 0 :(得分:1)

将以下代码放在执行(segue) viewWillDissappear 中,取决于您如何进行演示 - 通过故事板segue或手动从代码。

let backButton = UIBarButtonItem()
backButton.title = "whatever_you_want"
navigationItem.backBarButtonItem = backButton

vc2 viewDidLoad 中简单地放

navigationItem.title = "Controller title"

答案 1 :(得分:0)

我可以在故事板中更改它或在代码中更改它。

我通常这样做。

首先隐藏导航栏与默认导航控制器。

navigationController?.navigationBar.hidden = true

在故事板中创建导航栏并将其导出。

 @IBOutlet weak var navigationBar: UINavigationBar!

创建自定义导航项。

private lazy var customNavigationItem: UINavigationItem = {
    let navigationItem = UINavigationItem()
    let backButton = UIBarButtonItem(image: UIImage(named: "cancel_icon"), style: .Plain, target: self, action: #selector(cancelTapped))

    navigationItem.leftBarButtonItem = backButton
    navigationItem.title = "Your Title"

    return navigationItem
}()

将自定义导航项添加到导航栏

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    navigationController?.navigationBar.hidden = true
    navigationBar.setItems([customNavigationItem], animated: false)
}

希望有所帮助。