gpt4 book ai didi

ios - Swift:无法将自定义按钮添加到导航 Controller

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:15 26 4
gpt4 key购买 nike

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

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 集成这一事实是否会影响 View 的加载方式,但此自定义 NavigationController 正在被 TabBarController 中的每个选项卡子类化。

最佳答案

根据 UINavigationItem 类引用,每个 View Controller 都有自己的 UINavigationItem 实例。 “管理 UINavigationController 对象使用最上面的两个 View Controller 的导航项来用内容填充导航栏”,这意味着它的 UIViewController 负责创建导航项左栏项目或标题等内容。
我知道您想在整个应用程序中提供相同外观的导航栏。但是为什么要为所有 View Controller 设置相同的标题呢?但是,如果您需要所有 View Controller 的相同标题和相同左栏项目。这里有两个解决方案:
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
}
}

然后每当你需要一个 View Controller 的自定义导航栏时,你调用这个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() {

}
}

您的所有其他 View Controller 都将此 CustomViewController 子类化。

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

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

关于ios - Swift:无法将自定义按钮添加到导航 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37312604/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com