ios 11 - UIButton inside UIBarButtonItem causes an autolayout error

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

提交回复
热议问题