在没有使用 Interface Builder 的情况下,您可以通过编程方式在 UINavigationBar 中添加两个按钮。以下是一个简单的示例,展示了如何在右侧的 UINavigationBar 中添加两个按钮:
class YourViewController: UIViewController, UINavigationBarDelegate {
// ...
}
override func viewDidLoad() {
super.viewDidLoad()
// 设置导航栏代理
navigationController?.navigationBar.delegate = self
// 创建第一个按钮
let button1 = UIButton(type: .system)
button1.setTitle("Button 1", for: .normal)
button1.addTarget(self, action: #selector(button1Tapped), for: .touchUpInside)
let barButton1 = UIBarButtonItem(customView: button1)
// 创建第二个按钮
let button2 = UIButton(type: .system)
button2.setTitle("Button 2", for: .normal)
button2.addTarget(self, action: #selector(button2Tapped), for: .touchUpInside)
let barButton2 = UIBarButtonItem(customView: button2)
// 将两个按钮添加到数组中
navigationItem.rightBarButtonItems = [barButton1, barButton2]
}
@objc func button1Tapped() {
print("Button 1 tapped")
}
@objc func button2Tapped() {
print("Button 2 tapped")
}
这样,您就可以在右侧的 UINavigationBar 中添加两个按钮,而无需使用 Interface Builder。
领取专属 10元无门槛券
手把手带您无忧上云