Swift:无法向导航控制器添加自定义按钮

时间:2016-05-19 01:40:29

标签: ios swift uinavigationcontroller

我正在尝试创建自定义导航栏,但我很难修改导航栏的不同部分。我可以改变背景的颜色,但我似乎无法添加按钮或更改标题。

class CustomNavigationController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // changing the background color works
        self.navigationBar.barTintColor = UIColor.purpleColor()

        // none of this works
        let leftButton = UIBarButtonItem(title: "Info", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(openInfo))
        self.navigationItem.leftBarButtonItem = leftButton
        self.navigationItem.title = "MYTITLE"
    }
}

我不确定我是否正在尝试将此NavigationController与TabBarController集成,这会影响视图的加载方式,但这个自定义NavigationController正在被TabBarController中的每个选项卡子类化。

1 个答案:

答案 0 :(得分:0)

根据UINavigationItem类引用,每个视图控制器都有自己的UINavigationItem实例。 “管理UINavigationController对象使用最顶层的两个视图控制器的导航项来填充导航栏中的内容”,这意味着其UIViewController有责任创建导航项目内容,例如左栏项目或标题 我可以理解你想要在整个应用程序中提供相同的导航栏外观。但是为什么要为所有视图控制器设置相同的标题?但是,如果您需要所有视图控制器的相同标题和相同的左栏项目。这有两个解决方案:
1)。扩展为UIViewController

extension UIViewController {
    func customAppearance() {
        let leftButton = UIBarButtonItem(title: "Info", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(openInfo))
        self.navigationItem.leftBarButtonItem = leftButton
        self.navigationItem.title = "MYTITLE"
    }

    func openInfo() {
        // do what you want
    }
}

然后,只要您需要为视图控制器设置自定义导航栏,就可以调用此customAppearance函数:

    let vc = YourViewController()
    vc.customAppearance()

2)。子类UIViewController

class CustomViewController: UIViewController {
    override func viewDidLoad() {
        let leftButton = UIBarButtonItem(title: "Info", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(openInfo))
        self.navigationItem.leftBarButtonItem = leftButton
        self.navigationItem.title = "MYTITLE"
    }

    func openInfo() {

    }
}

您的每个其他视图控制器都将此CustomViewController子类化。

要自定义UINavigationBar的外观,您可以将其设置为:

UINavigationBar.appearance().barTintColor = UIColor.purpleColor()