我正在尝试对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
如您在视频中所见,该按钮可以正常工作,但标签无法正常工作。
我尝试了调查并从
MyLabel
类创建了子类。看起来,在动画块中的[self.label layoutIfNeeded];
导致- (void)drawTextInRect:(CGRect)rect
立即被调用。为什么会这样?我希望框架能够根据设置在动画块内的方式进行动画变化,就像UIButton那样。但对于UILabel却没有按预期工作。为什么UILabel不能执行动画缩放?有没有方法可以修复它?
编辑: 我已经尝试了目前答案中提出的方法,但它们也不起作用。我认为动画代码不是问题,因为它在我的示例中适用于按钮。问题似乎与UILabel特定有关。UILabel似乎处理大小更改的动画方式与其他UIView子类不同,但我无法理解原因。
self.label3.text
但是ViewController
没有label3
属性。当你不展示真实的代码时,很难帮助你。无论如何,我怀疑在 storyboard 中设置标签的方式存在问题。 - rob mayoff