1

Can programmatically move the position of Add UIBarButtonItem to the right of the navigation bar. I already have a button there when the button is hidden, I want to move Add button to its position. I used this code to hide the right cornerBtn:

  if arrayAddress.isEmpty == true{
     navigationItem.rightBarButtonItem?.title = ""

        }

If there is no item in tableview the Edit button will be hidden and the plus button move to the corner. My question how can I move plus button?

Here is an image explaining my question

1 Answers1

0

You want to set the .rightBarButtonItems property. You can change this as needed.

So, for example, we'll start with only the + button showing, and when it is tapped we'll also show the Edit button:

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]

    }
}
DonMag
  • 69,424
  • 5
  • 50
  • 86