How to change UIBarButtonItem text during runtime

2019-06-14 13:22发布

问题:

I'm trying to change UIBarButtonItem text "cleanly" during runtime so that Edit/Done modes can be toggled. Every time I change the title attribute during runtime, however, the animation seems clumsy. I'm looking to emulate the appearance and function of the Edit/Done button in the Contacts app (where Edit simply fades and Done appears in its place).

@IBAction func editDoneButtonPressed(sender: UIBarButtonItem) {

    if(sender.title == "Edit"){
        sender.title = "Done"
    }else{
        sender.title = "Edit"
    }

}

Initial settings: Identifier is set to "custom" and Title is set to "Edit"

Simpler programatical solutions are preferred, however, the appearance of the animation is indeed paramount. I'd consider toggling the UIBarButtonItem identifier, rather than its text attribute, however, I'm not sure of an elegant way to toggle the identifier during runtime.

BTW: I'm using Swift to construct the app.

Links to...

Screencast of Contacts app Edit/Done toggle animation: https://youtu.be/5mT_vzpNhIw

Screencast of my Edit/Done toggle animation: https://youtu.be/mEweotJNVNE

Thank you.

回答1:

There's a much better way, a standard way, to get an Edit/Done button.

UIViewController provides a standard Edit/Done button that is already hooked into the editing property of the view controller.

A common usage is as follows:

Inside the viewDidLoad method of your view controller, use the standard button:

self.navigationItem.rightBarButtonItem = editButtonItem

Put the editButtonItem wherever you actually need it.

Then, instead of setting up your own action, simply override the setEditing(_:animated:) method:

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)
    }
}