ios 11 - UIButton inside UIBarButtonItem causes an autolayout error

前端 未结 3 1816
甜味超标
甜味超标 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 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).

提交回复
热议问题