UIButton in subview doesn't get touch after NSLayoutConstraint

I have 2 custom UIViews that I add to my UIViewController and then align them using NSLayoutConstraint. After I applied NSLayoutConstraint in the UIViewController view, the UIButtons in custom UIViews no longer receive touch events.

- (void)viewDidLoad { [super viewDidLoad]; navigationBar = [[DtNavigationBar alloc] initWithFrame:CGRectMake(0,0,320,45)]; [navigationBar setTranslatesAutoresizingMaskIntoConstraints:NO]; [self.view addSubview:navigationBar]; switchBar = [[DtSwitch alloc] initWithFrame:CGRectMake(0,0,320,44)]; [switchBar setTranslatesAutoresizingMaskIntoConstraints:NO]; [self.view addSubview:switchBar]; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[navigationBar(45)]-0-[switchBar(44)]-(>=100)-|" options:NSLayoutFormatAlignAllLeft metrics:nil views:NSDictionaryOfVariableBindings(switchBar, navigationBar)]]; } 

Both DtNavigationBar and DtSwitch have UIButton views that still display in the right place but no longer respond to touch.

If I remove the addConstraints part (and manually place the views), then the buttons will work fine.

+5
ios autolayout
source share
1 answer

The problem is that when you decide to use restrictions, you are not using enough restrictions. You have an ambiguous layout.

To test this hypothesis, run the application and run it in the debugger and enter it in the lldb console:

 po [[UIWindow keyWindow] _autolayoutTrace] 

The words AMBIGUOUS LAYOUT will appear somewhere in the answer.

You need enough restrictions to make these words go away. You must fully determine the vertical and horizontal position, width and height of everything in the story.

+14
source share

All Articles