如何在运行时“干净地”更改UIBarButtonItem文本(编辑 – >完成 – >编辑)?

我试图在运行期间“干净地”更改UIBarButtonItem文本,以便编辑/完成模式可以切换。 每次我在运行时改变title属性,animation看起来都很笨拙。 我正在模拟“通讯录”应用程序中的“编辑/完成”button的外观和function(其中“编辑”只是淡入淡出,“完成”处于显示位置)。

@IBAction func editDoneButtonPressed(sender: UIBarButtonItem) { if(sender.title == "Edit"){ sender.title = "Done" }else{ sender.title = "Edit" } } 

初始设置:标识符设置为“自定义”,标题设置为“编辑”

更简单的编程解决scheme是首选,然而,animation的外观确实是最重要的。 我会考虑切换UIBarButtonItem标识符,而不是它的文本属性,但是,我不确定在运行时切换标识符的优雅方式。

顺便说一句:我正在使用Swift来构build应用程序。

链接到…

截屏的通讯录应用程序编辑/完成切换animation: https : //youtu.be/5mT_vzpNhIw

我的编辑/完成切换animation的截屏: https : //youtu.be/mEweotJNVNE

谢谢。

有一个更好的方法,一个标准的方法,得到一个编辑/完成button。

UIViewController提供了一个标准的Edit / Donebutton,它已经被挂钩到视图控制器的editing属性中。

常用的用法如下:

在视图控制器的viewDidLoad方法内部,使用标准button:

 self.navigationItem.rightBarButtonItem = editButtonItem 

editButtonItem放到你真正需要的地方。

然后,不要设置自己的操作,只需重写setEditing(_:animated:)方法:

 override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) if (editing) { // user just tapped the Edit button (it now says Done) } else { // user just tapped the Done button (it now says Edit) } }