I put together a simple view controller programmatically using two buttons on it. If I go to an old school and set the size of the frame for the layout, then everything will be fine. However, if I use layout restrictions for the layout, the buttons are displayed fine, but they do not respond to clicks. They don’t even give out. My loadview method is given below in a form that does not allow buttons to work. If the frame setting code is uncommented, and the addition of restrictions is added, then the buttons begin to respond to clicks as expected. Does anyone know what is going on? I would like to translate all the old hard code in my code base to be based on restrictions, but it seems to fall on the first hurdle.
- (void)loadView { self.view = [UIView new]; self.view.translatesAutoresizingMaskIntoConstraints = NO; self.navigationItem.title = @"Landing Page"; UIButton *buildExercisesButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; self.buildExercisesButton = buildExercisesButton; // buildExercisesButton.frame = CGRectMake(20, 312, 164, 44); self.buildExercisesButton.translatesAutoresizingMaskIntoConstraints = NO; [self.buildExercisesButton setTitle:@"Build Exercises" forState:UIControlStateNormal]; [self.buildExercisesButton addTarget:self action:@selector(buildExercisesButtonPressed) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:self.buildExercisesButton]; UIButton *organiseExercisesButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; self.organiseExercisesButton = organiseExercisesButton; // organiseExercisesButton.frame = CGRectMake(192, 312, 164, 44); self.organiseExercisesButton.translatesAutoresizingMaskIntoConstraints = NO; [self.organiseExercisesButton setTitle:@"Organise Exercises" forState:UIControlStateNormal]; [self.organiseExercisesButton addTarget:self action:@selector(organiseExercisesButtonPressed) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:self.organiseExercisesButton]; NSDictionary *variables = NSDictionaryOfVariableBindings(buildExercisesButton, organiseExercisesButton); NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|-[buildExercisesButton(organiseExercisesButton)]-[organiseExercisesButton]-|" options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:nil views:variables]; [self.view addConstraints:constraints]; constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[buildExercisesButton]-|" options:0 metrics:nil views:variables]; [self.view addConstraints:constraints]; }
In viewDidAppear, I print the button frames. They give strange values that I don’t know if this is connected or not. Buttons are actually displayed next to each other in the center of the screen.
buildExercisesButton: {{20, -63}, {164, 44}} organiseExercisesButton: {{192, -63}, {164, 44}}
source share