我以编程方式组合了一个简单的视图控制器,上面只有两个按钮。如果我去老学校并为布局设置框架大小,那么一切都很好。但是,如果我对布局使用自动布局约束,那么按钮会完美显示,但它们不会响应按下。他们甚至没有突出显示。我的 loadview 方法在下面的表单中,使按钮不起作用。如果框架设置代码未注释并且添加的约束被注释掉,则按钮开始按预期响应按下。有谁知道发生了什么?我很想将我的代码库中的所有旧硬编码布局转换为基于约束的,但似乎在第一个障碍中落下。
- (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];
}
在 viewDidAppear 中,我打印出按钮的框架。他们给出了奇怪的值,我不知道它是否相关。实际上,这些按钮在屏幕中央并排显示。
buildExercisesButton: {{20, -63}, {164, 44}}
organiseExercisesButton: {{192, -63}, {164, 44}}