我正在尝试以编程方式添加 UIBarButtonItem。
let navigation = UINavigationController()
let rightBarButton = UIBarButtonItem(title: "LogIn", style: .plain, target: self, action: #selector(logInPressed))
navigation.navigationItem.rightBarButtonItem = rightBarButton
并且还制作了一个选择器函数用于测试。
@objc func logInPressed() {
print("go to login")
}
不幸的是,这不起作用 - 模拟器中的导航栏上看不到栏按钮。
使用断点检查,rightBarButtonItem 存在。
问题可能是由应用程序协调器而不是子 VC 创建栏按钮引起的。
请问有人可以帮忙解决这个问题吗? Simulator screenshot
最佳答案
您正在将 UIBarButtonItem 添加到 NavigationController 的新实例。所以它不会出现在那里。
因此,在您想要处理右侧导航栏的 View Controller 中,使用以下方法之一:
覆盖 func viewDidLoad()
或者
覆盖 func viewWillAppear
添加:
let rightBarButton = UIBarButtonItem(title: "LogIn", style: .plain, target: self, action: #selector(logInPressed))
self.navigationController?.navigationItem.setRightBarButton(rightBarButton, animated: true)
关于swift - 以编程方式添加 UIBarButtonItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59481857/