gpt4 book ai didi

ios - 带有自动布局的 UILabel 高度动画

转载 作者:可可西里 更新时间:2023-11-01 04:35:08 29 4
gpt4 key购买 nike

我的 View 和 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];
}];
}

最佳答案

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

所以新方法:

- (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];
}];
}

关于ios - 带有自动布局的 UILabel 高度动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21261413/

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