ios 11 - UIButton inside UIBarButtonItem causes an autolayout error

前端 未结 3 1789
甜味超标
甜味超标 2021-01-12 05:39

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

相关标签:
3条回答
  • 2021-01-12 05:58

    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)];
    
    0 讨论(0)
  • 2021-01-12 06:14

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

    0 讨论(0)
  • 2021-01-12 06:20

    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)
    
    0 讨论(0)
提交回复
热议问题