ios 11 - UIButton inside UIBarButtonItem causes an autolayout error

巧了我就是萌 提交于 2019-12-05 07:21:44

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)

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).

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)];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!