【问题标题】:Swift: Can't add custom button to navigation controllerSwift:无法将自定义按钮添加到导航控制器
【发布时间】:2016-09-15 16:58:08
【问题描述】:

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

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 中的每个选项卡子类化。

【问题讨论】:

    标签: ios swift uinavigationcontroller


    【解决方案1】:

    根据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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 2021-06-27
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多