0

I want to center UIBarButtonItems in a UINavigationBar at the top of the screen. While still with UIBarButtonItems on the left and right sides.

This is what I have tried already: (I am just using the .add icon for now to just make sure I have the formatting correct.

        thumbnailButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: nil)
        eraserButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: nil)
        scissorButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: nil)
        pencilButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: nil)
        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
        let flexibleSpace2 = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
        let undoButtonItem = UIBarButtonItem(barButtonSystemItem: .undo, target: self, action: nil)
        let shareButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: nil)

        navigationItem.leftItemsSupplementBackButton = true
        navigationItem.leftBarButtonItems = [thumbnailButton]
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        navigationItem.rightBarButtonItems = [shareButtonItem, flexibleSpace, undoButtonItem, scissorButton, pencilButton, eraserButton]

This is what I am trying to make it look like image

steveSarsawa
  • 1,559
  • 2
  • 14
  • 31

1 Answers1

0

According to Apple documentation:

navigationItem.titleView

If this property value is nil, the navigation item’s title is displayed in the center of the navigation bar when the receiver is the top item. If you set this property to a custom title, it is displayed instead of the title.

Custom views can contain buttons. Use the init(type:) method in UIButton class to add buttons to your custom view in the style of the navigation bar. Custom title views are centered on the navigation bar and may be resized to fit.

The default value is nil.

You can do it in two ways :

    navigationItem.title = nil
    let barButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: nil)
    barButtonItem.customView = UIView(frame: CGRect(x: 10, y: 10, width: 10, height: 10))
    navigationItem.titleView?.addSubview(barButton.customView!)

Or

    navigationItem.title = nil
    let button = UIButton(type: .system)
    navigationItem.titleView?.addSubview(button)    
Celeste
  • 1,519
  • 6
  • 19