gpt4 book ai didi

ios - 使用自动布局时 UIButton 停止工作

转载 作者:可可西里 更新时间:2023-11-01 03:49:23 26 4
gpt4 key购买 nike

我以编程方式将一个简单的 View Controller 放在一起,上面只有两个按钮。如果我去老学校并为布局设置框架大小,那么一切都很好。但是,如果我对布局使用自动布局约束,那么按钮会完美显示,但它们不会响应按键。他们甚至不强调。我的 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}}

最佳答案

您需要为要添加按钮的 View 定义约束或将 translatesAutoresizingMaskIntoConstraints 属性设置为 YES

关于ios - 使用自动布局时 UIButton 停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18771303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com