I\'ve a known issue with adding a UIButton into UIBarButtonItem. I\'ve tried to add auto layout constraints as suggested in stackoveflow but I\'m getting an error described
Use this simple way to create button with auto layout. Create button will have with flexible width according to size of the UIView. There is no need to add extra constraints.
UIButton *sortButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sortButton setFrame:CGRectMake(10, 0, self.view.frame.size.width - 10, 30)];
I've had this issue also since iOS11. I solved it by creating a custom view with it's own XIB and place a button in it. Then you can easily set the constraints within InterfaceBuilder in the XIB. Then when you actually want to use it in a barbuttonitem, the code is very short:
self.customButtonView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([CustomButtonView class]) owner:nil options:nil] objectAtIndex:0];
[self.customButtonView.button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.customButtonView];
Just don't forget the second line where you actually have to assign a selector for the button (which is an IBOutlet in the custom view of course).
The bar button is constrained to the left and right, so the width constraint has to be broken. You can fix this by adding a flexible space to the toolbar. This allows you to contraint the width of the button and have the flexible space fill the rest.
Obj C:
UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[self setToolbarItems:[NSArray arrayWithObjects:self.sortCollection, flexItem, nil]];
Swift:
let flexItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolbar.setItems([barButtonItem, flexItem], animated: false)