我正在使用位于屏幕右侧的 UIBarButtonItem
创建一个 NavigationBar
。默认情况下,我将 setRightBarButton
设置为 UIBarButtonItem(image: UIImage(named: "edit"), style: .plain, target: self, action: #selector(editProfile))
当我点击它时,它应该将 rightBarButton
更改为其他标题,但它不起作用。
这是我尝试通过点击它来改变
@objc
func editProfile() {
self.navigationItem.setRightBarButton(cancelActionBar, animated: true)
}
这是cancelActionBar
的对象
let cancelActionBar = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelEdit))
这是将其更改回默认值的操作。
@objc
func cancelEdit() {
self.navigationItem.setRightBarButton(editActionBar, animated: true)
}
我也尝试过使用主线程,但它没有像我预期的那样工作。
最佳答案
当您创建一个 UIBarButtonItem
作为实例属性时,目标 self
将不会被初始化。所以设置目标 self
是行不通的。
class ViewController: UIViewController {
let editActionBar = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editBtnAction(_:)))
override func viewDidLoad() {
super.viewDidLoad()
print(editActionBar.target)//nil
}
}
目标 self
将在您初始化 viewDidLoad
中的按钮时正确分配
class ViewController: UIViewController {
var editActionBar: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
editActionBar = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editBtnAction(_:)))
print(editActionBar?.target)//self
}
}
将按钮声明为可选按钮并在 viewDidLoad 中初始化按钮。
class ViewController: UIViewController {
var editActionBar: UIBarButtonItem?
var cancelActionBar: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
self.editActionBar = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editBtnAction(_:)))
self.cancelActionBar = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelBtnAction(_:)))
self.navigationItem.setRightBarButton(editActionBar, animated: true)
}
@objc func editBtnAction(_ sender: UIBarButtonItem) {
self.navigationItem.setRightBarButton(cancelActionBar, animated: true)
}
@objc func cancelBtnAction(_ sender: UIBarButtonItem) {
self.navigationItem.setRightBarButton(editActionBar, animated: true)
}
}
关于ios - 动态更改导航栏项目 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56390608/