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

前端之家收集整理的这篇文章主要介绍了ios – UIButton在使用自动布局时停止工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我用编程方式组装了一个简单的视图控制器,上面只有两个按钮.如果我去学校并为布局设置框架大小,那么一切都很好.但是,如果我对布局使用自动布局约束,则按钮显示完美,但它们不响应按下.他们甚至没有强调.我的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,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,44}}

解决方法

您需要为要添加按钮的视图定义约束,或将translatesAutoresizingMaskIntoConstraints属性设置为YES.
原文链接:https://www.f2er.com/iOS/328336.html

猜你在找的iOS相关文章