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

Solution 1:

UIBarButtonItem *fixedItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
fixedItem.width = 20.0f; // or whatever you want

UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

Solution 2:

Swift

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

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

Solution 3:

UIBarButtonItem *todayItem = [[UIBarButtonItem alloc] initWithTitle:@"Today" style:UIBarButtonItemStylePlain target:self action:@selector(update_baritem:)];
todayItem.tag = 2;

UIBarButtonItem *cashItem = [[UIBarButtonItem alloc] initWithTitle:@"Cash" style:UIBarButtonItemStylePlain target:self action:@selector(update_baritem:)];
cashItem.tag = 3;

UIBarButtonItem *creditItem = [[UIBarButtonItem alloc] initWithTitle:@"Credit" style:UIBarButtonItemStylePlain target:self action:@selector(update_baritem:)];
creditItem.tag = 4;

UIBarButtonItem *allItem = [[UIBarButtonItem alloc] initWithTitle:@"All" style:UIBarButtonItemStylePlain target:self action:@selector(update_baritem:)];
allItem.tag = 1;

UIBarButtonItem *returnItem = [[UIBarButtonItem alloc] initWithTitle:@"Return" style:UIBarButtonItemStylePlain target:self action:@selector(update_baritem:)];
returnItem.tag = 5;

UIBarButtonItem *fixedItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[fixedItem setWidth:455.0f];

UIBarButtonItem *fixed2Item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[fixed2Item setWidth:37.0f];

UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

[self.toolbar setItems:@[fixed2Item, returnItem, creditItem, cashItem, fixedItem, todayItem, flexibleItem, allItem] animated:NO];

Solution 4:

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)