具有自动布局的UILabel高度动画

som*_*dev 5 uilabel ios autolayout

我的观点和UIButton都有一个UILabel.当按钮触摸UILabel时应更改动画高度,取决于标签内容.我在尝试这个:

    - (void)viewDidLoad {
        self.textLabel= [[UILabel alloc] initWithFrame:CGRectZero];
        self.textLabel.numberOfLines=0;
        self.textLabel.font= [UIFont systemFontOfSize:14];
        self.textLabel.backgroundColor= [UIColor lightGrayColor];
        self.textLabel.text= @"short text";
        [self.view addSubview:self.textLabel];
        [self.textLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[_textLabel]-10-|"
        options:0
        metrics:nil
        views:NSDictionaryOfVariableBindings(_textLabel)]];


        self.button= [UIButton buttonWithType:UIButtonTypeSystem];
        [self.button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
        [self.button setTitle:@"Tap" forState:UIControlStateNormal];
        self.button.backgroundColor= [UIColor greenColor];
        [self.button setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.view addSubview:self.button];

        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[_button]-10-|"
                                   options:0
                                   metrics:nil
                                   views:NSDictionaryOfVariableBindings(_button)]];

        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-50-[_textLabel(>=0)]-10-[_button(==20)]"
                                   options:0
                                   metrics:nil
                                    views:NSDictionaryOfVariableBindings(_textLabel,_button)]];

}

- (void)buttonTouched:(id)buttonTouched {
        self.shortText =!self.shortText;
        self.textLabel.text= self.shortText ?@"short text":@"long long long text\nlong long long text\nlong long long text\n";
        [UIView animateWithDuration:1.0
                         animations:^{
                             [self.view layoutIfNeeded];
                     }];
}
Run Code Online (Sandbox Code Playgroud)

And*_*sek 5

在动画块之前,您需要调用[self.view setNeedsUpdateConstraints]以便在调用时触发告诉视图需要更新约束layoutIfNeeded

所以新方法:

- (void)buttonTouched:(id)buttonTouched {
    self.shortText =!self.shortText;
    self.textLabel.text= self.shortText ?@"short text":@"long long long text\nlong long long text\nlong long long text\n";
    [self.view setNeedsUpdateConstraints];
    [UIView animateWithDuration:1.0
                     animations:^{
                         [self.view layoutIfNeeded];
    }];
}
Run Code Online (Sandbox Code Playgroud)


Art*_*are 0

在故事板中定义高度约束,将其添加为 IBOutlet,然后在动画块内更改其值。