Autostart inside UIBarButtonItem user view

I am having a strange problem with UIBarButtonItem . I create one with a custom view, and the view has its own type MyCustomView . It contains a couple of shortcuts and some other sub-items. Whenever I use autolayout in this custom view class to lay out routines - the button appears in the upper left corner of the screen! You can see it in the picture below - MyCustomView has only one preview with a gray background, and I use autostart to stretch it to fill the parent MyCustomView :

wrong

When I do not use autostart, everything is fine, and the button is displayed normally:

right

Can someone explain to me what is happening here, and is it allowed to use autorun in custom views that will be placed in a UIBarButtonItem (maybe not at the very top level)?

UPDATE: this happens after I do

  self.translatesAutoresizingMaskIntoConstraints = NO; 

in MyCustomView - in the top view, which should be placed in the bar button. I do this so that the system calls my intrinsicContentSize method. I assume using the old sizeThatFits: will be okay anyway.

UPDATE 2: Here is the test code:

 UIControl *cus = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 22, 22)]; // uncomment the following line to mess everything //cus.translatesAutoresizingMaskIntoConstraints = NO; cus.backgroundColor = [UIColor redColor]; UILabel *label = [UILabel new]; label.translatesAutoresizingMaskIntoConstraints = NO; label.text = @"Q"; [label sizeToFit]; label.font = [UIFont systemFontOfSize:18]; [cus addSubview:label]; NSLayoutConstraint *centerX1 = [NSLayoutConstraint constraintWithItem:cus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:label attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]; NSLayoutConstraint *centerY1 = [NSLayoutConstraint constraintWithItem:cus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:label attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]; [cus addConstraints:@[centerX1, centerY1]]; UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:cus]; controller.navigationItem.rightBarButtonItem = barButton; 

I would be happy to receive an explanation to understand what is happening.

+5
source share

Source: https://habr.com/ru/post/1236198/


All Articles