簡體   English   中英

為什么UILabel邊界上的動畫僅在增大尺寸時起作用?

[英]Why are animations on bounds of an UILabel only working when increasing the size?

我注意到當我在動畫塊中更改UILabel的邊界時,它只有在我增加大小時才有效,當我減小大小時UILabel只是改變了它的大小但沒有動畫。 用普通的UIView替換UILabel按預期工作。

注意:將UILabel的contentMode屬性更改為UIViewContentModeScaleToFill可以解決此問題,但我仍然不明白為什么在增加大小而不更改contentMode屬性時它可以正常工作。

#import "FooView.h"

@interface FooView ()
@property (strong, nonatomic) UILabel   *label;
@property (assign, nonatomic) BOOL       resized;
@end

@implementation FooView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor lightGrayColor];

        self.label = [[UILabel alloc] initWithFrame:(CGRect){0, 0, frame.size}];
        self.label.backgroundColor = [UIColor greenColor];
        [self addSubview:self.label];
        _resized = false;

        UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeSize)];
        tapRecognizer.numberOfTapsRequired = 1;
        [self addGestureRecognizer:tapRecognizer];
    }
    return self;
}

- (void)changeSize {
    [UIView animateWithDuration:0.8
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         CGRect bounds = self.label.bounds;
                         if (self.resized) {
                             bounds.size.height *= 2;
                             bounds.size.width  *= 2;
                         } else {
                             bounds.size.width  /= 2;
                             bounds.size.height /= 2;
                         }
                         self.label.bounds = bounds;
                     }
                     completion:^(BOOL finished) {
                         self.resized = !self.resized;
                     }];
}

@end

這是因為UILabel將其圖層的contentsGravity設置為正在呈現文本的方向,這恰好默認為UIViewContentModeLeft (或@"left" )。 因此,當告訴該層動畫時,它首先看一眼其內容的重力並將隨后的動畫置於其上。 因為它看到@"left"應該有@"resize" ,它假定縮放動畫應該從左邊開始,但它也必須尊重你給它的約束(邊界變化),所以你的標簽似乎跳到它的最終大小,然后在屏幕中央的位置。

如果您想單獨保留contentMode ,請使用CATransform3D並以此方式縮放標簽的圖層而不是邊界更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM