【发布时间】:2016-01-08 18:16:41
【问题描述】:
我正在尝试为 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]; 的原因。为什么会这样?我希望帧被更改为动画,因为它设置在动画块内。对于 UIButton,它按预期工作。
为什么 UILabel 不调整动画大小?有办法解决吗?
编辑: 我尝试了当前答案中建议的方法,但它们也不起作用。我认为动画代码在这里不是问题,因为它适用于我的示例中的按钮。该问题似乎与特定于 UILabel 的问题有关。 UILabel 处理大小变化的动画似乎与其他 UIView 子类不同,但我不明白为什么。
【问题讨论】:
-
您的代码显示了篡改的证据:它设置了
self.label3.text,但ViewController没有label3属性。当您不向我们展示您的真实代码时,很难为您提供帮助。无论如何,我怀疑你的标签在情节提要中的设置方式存在问题。
标签: ios objective-c uiviewanimation ios-autolayout