我正在嘗試動畫UILabel的寬度。出於某種原因,動畫不起作用,標籤立即改變大小。我使用自動佈局。這裏是我寫的重現這個示例項目的代碼。點擊按鈕可更改按鈕和標籤的尾隨限制。使用自動佈局動畫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
類調查和subclassed標籤。看起來,- (void)drawTextInRect:(CGRect)rect
立即被按鈕按鈕調用,作爲[self.label layoutIfNeeded];
在動畫塊中的原因。爲什麼這樣?我會期望幀被改變爲動畫,因爲它被設置在動畫塊內。它和UIButton的預期一樣。
爲什麼UILabel不調整動畫大小?有沒有辦法解決它?
編輯: 我嘗試了當前答案中提出的方法,但它們也不起作用。我認爲動畫代碼在這裏不是問題,因爲它適用於我的示例中的按鈕。這個問題似乎與UILabel具體有關。 UILabel似乎處理動畫的大小變化不同於其他UIView子類,但我不明白爲什麼。
你的代碼顯示篡改的證據:它集'自我。 label3.text'但是'ViewController'沒有'label3'屬性。當你沒有向我們展示你真實的代碼時,很難幫助你。無論如何,我懷疑你的標籤在故事板中的設置方式存在問題。 –