How to create fixed space and flexible space bar button items programmatically?

Viewed 76935

I want to create UIBarButtonItems programmatically and place these fixed space items between buttons.

8 Answers

In Swift:

let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
fixedSpace.width = 20.0

As of this writing, if you're targeting iOS 14 and above, you can use the corresponding class functions to get fixed and flexible space items more concisely:

let fixedSpace = UIBarButtonItem.fixedSpace(20)
let flexibleSpace = UIBarButtonItem.flexibleSpace()

Docs: fixed space, flexible space

Swift 5.1.2

// Fixed Space
let fixedSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
fixedSpace.width = 20.0

// Flexible Space
let flexibleSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
Related