Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton in subview not receiving touch after NSLayoutConstraint

Tags:

ios

autolayout

I have 2 custom UIViews that i'm adding to my UIViewController and then aligning them using NSLayoutConstraint. After I apply the NSLayoutConstraint on the UIViewController view then UIButtons in the 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 show up in the right place but no longer responds to touch.

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

like image 608
Lasse Hassing Avatar asked May 18 '13 22:05

Lasse Hassing


1 Answers

The problem is that, having elected to use constraints, you are not using enough constraints. You have ambiguous layout.

To test this hypothesis, run the app, and pause in the debugger and enter this in the lldb console:

po [[UIWindow keyWindow] _autolayoutTrace]

The words AMBIGUOUS LAYOUT will appear somewhere in the response.

You need sufficient constraints to make those words go away. You must fully determine the vertical and horizontal position and width and height of everything in the story.

like image 183
matt Avatar answered Sep 25 '22 01:09

matt