xcode导航栏按钮状态

时间:2019-03-15 07:03:11

标签: swift xcode button state

我有一个编辑按钮-UIBarButtonItem

enter image description here

点击后消失在屏幕上

enter image description here

并在单击取消按钮时出现

enter image description here

如您所见,编辑按钮的状态在出现后保持选中状态。 如何以编程方式将导航栏按钮状态更改为正常状态?或者建议我一个更好的方法。

这是我的项目代码

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, introductionDelegate {

var navBarEditButton: UIBarButtonItem?
var navBarDeleteButton: UIBarButtonItem?
var navBarCancelButton: UIBarButtonItem?

override func viewDidLoad() {
    super.viewDidLoad()
    self.navBarEditButton = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editObjectsAction))
    self.navBarDeleteButton = UIBarButtonItem(title: "Delete", style: .plain, target: self, action: #selector(deleteObjectsAction))
    self.navBarCancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelAction))

    self.navigationItem.leftBarButtonItems = [navBarEditButton!]
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@objc private func editObjectsAction(_ sender: UIBarButtonItem) {
    self.navigationItem.leftBarButtonItems = [navBarCancelButton!, navBarDeleteButton!]
}

@objc private func cancelAction(_ sender: UIBarButtonItem) {
    self.navigationItem.leftBarButtonItems = [navBarEditButton!]
}

@objc private func deleteObjectsAction(_ sender: UIBarButtonItem) {

}

2 个答案:

答案 0 :(得分:1)

您可以使用UIBarButtonItem创建UIButton并处理该按钮上的状态。这样,您可以更改UIBarButtonItem样式,但只需检查是否获得预期的结果即可。

let myButton = UIButton(frame: CGRect(x: 10, y: 300, width: 100, height: 40)) // handle state on this button
self.navBarEditButton = UIBarButtonItem(customView: myButton)

答案 1 :(得分:0)

我添加了一个新功能

func refreshNavBarButton (navBarButton: inout UIBarButtonItem) {
    navBarButton = UIBarButtonItem(title: navBarButton.title, style: navBarButton.style, target: navBarButton.target, action: navBarButton.action)
}

我每次在导航栏按钮显示之前都叫它

    refreshNavBarButton(navBarButton: &navBarEditButton!)
    self.navigationItem.leftBarButtonItems = [navBarEditButton!]