swift - 以编程方式添加 UIBarButtonItem

标签 swift uinavigationcontroller uibarbuttonitem swift5

我正在尝试以编程方式添加 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/

相关文章:

iphone - 是否可以将 UIBarButtonItem 作为单元格accessoryView?

ios - 在设备屏幕上运行时不会出现填充屏幕

ios - 减少 uibarbuttonitem 的宽度

ios - 同步 TabBar/NavigationBar 上的背景颜色

swift : Convert 12hr time to 24hrs when device is in 12hrs formate

ios - 在 PageViewController 导航不工作

iphone - 如何在 UINavigationController 中正确继承 UITableViewController?

ios - 在 MPRemoteCommandEvent iOS 中获取错误的时间戳

ios - 如何快速过滤字符串并获得中间结果

ios - `UTF16Index()` 或 `UTF16Index.init(encodedOffset:)` 用于 Xcode 8/9 支持