能否通过编程将Add UIBarButtonItem的位置移动到导航栏的右边。我已经在那里有一个按钮,当按钮被隐藏时,我想把Add按钮移动到它的位置。我使用这段代码隐藏了右边的 cornerBtn。
if arrayAddress.isEmpty == true{
navigationItem.rightBarButtonItem?.title = ""
}
如果tableview中没有项目,编辑按钮将被隐藏,加号按钮将移动到角落。我的问题是如何移动加号按钮?
您要设置的是 .rightBarButtonItems
属性。你可以根据需要来更改。
所以,举例来说,我们将从只使用 +
按钮,而当它被点击时,我们也会显示出 Edit
按钮。
class TestViewController: UIViewController {
lazy var addButton: UIBarButtonItem = {
let b = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(self.myAddAction(_:)))
return b
}()
lazy var editButton: UIBarButtonItem = {
let b = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(self.myEditAction(_:)))
return b
}()
@objc func myAddAction(_ sender: Any) -> Void {
print("Add button tapped!")
// this will add both buttons
self.navigationItem.rightBarButtonItems = [editButton, addButton]
}
@objc func myEditAction(_ sender: Any) -> Void {
print("Edit button tapped!")
}
override func viewDidLoad() {
super.viewDidLoad()
// let's start with only the "add" button,
// and show the "edit" button after the add button has been tapped
self.navigationItem.rightBarButtonItems = [addButton]
}
}