gpt4 book ai didi

ios - 使用自动布局动画化 UILabel 宽度

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:06:11 25 4
gpt4 key购买 nike

我正在尝试为 UILabel 的宽度设置动画。由于某种原因,动画不起作用并且标签会立即更改其大小。我使用自动布局。这是我为重现此代码而编写的示例项目中的代码。点击按钮会更改按钮和标签的尾随约束。

@interface ViewController ()

@property (assign, nonatomic) BOOL controlsResized;
@property (weak, nonatomic) IBOutlet UIButton *button;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttonTrailingConstraint;
@property (weak, nonatomic) IBOutlet MyLabel *label;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelTrailingConstraint;
- (IBAction)doTapButton:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

[self.button setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.label setTranslatesAutoresizingMaskIntoConstraints:NO];
self.label3.text = @"asdfasdfds sklfjfjls sdlkfj jjjjkfjkfdsjkdfsjklffsjkfdsjkl";
}


- (IBAction)doTapButton:(id)sender
{
if (!self.controlsResized)
{
[UIView animateWithDuration:0.5 animations:^{
self.buttonTrailingConstraint.constant = 0;
[self.button layoutIfNeeded];
self.labelTrailingConstraint.constant = 0;
[self.label layoutIfNeeded];

self.controlsResized = YES;
}];
}
else
{
[UIView animateWithDuration:0.5 animations:^{
self.buttonTrailingConstraint.constant = 100;
[self.button layoutIfNeeded];
self.labelTrailingConstraint.constant = 100;
[self.label layoutIfNeeded];

self.controlsResized = NO;
}];
}
}

@implementation MyLabel

- (void)drawTextInRect:(CGRect)rect
{
NSLog(@"drawTextInRect");
[super drawTextInRect:rect];
}

@end

正如您在 video 上看到的那样,它适用于按钮,但不适用于标签。

我试图调查 MyLabel 类的标签并将其子类化。看起来,- (void)drawTextInRect:(CGRect)rect 在点击按钮时立即被调用,因为 [self.label layoutIfNeeded]; 在动画中堵塞。为什么会这样?我希望框架可以更改为动画,因为它是在动画 block 内设置的。它按 UIButton 的预期工作。

为什么 UILabel 不调整动画大小?有办法解决吗?

编辑:我尝试了当前答案中建议的方法,但它们也不起作用。我认为动画代码在这里不是问题,因为它适用于我示例中的按钮。该问题似乎与特定于 UILabel 的问题有关。 UILabel 似乎以不同于其他 UIView 子类的方式处理大小变化的动画,但我不明白为什么。

最佳答案

我会发表评论,但我没有必要的声誉。这是我会做的:

self.buttonTrailingConstraint.constant = x;
self.labelTrailingConstraint.constant = x;

[UIView animateWithDuration:0.5 animations:^{

[self.view layoutIfNeeded];
}];

当您更新约束时,您需要考虑到您正在修改的各个 View 的约束不是唯一需要更新的约束,因此最好在父 View 上调用布局方法。

这每次都对我有用。希望这会有所帮助。

关于ios - 使用自动布局动画化 UILabel 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34683530/

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