ios – 为什么UILabel的边界上的动画只能在增加大小时起作用?

我注意到,当我改变一个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,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将其层的contentGravity设置为正在呈现的文本方向,这恰好认为UIViewContentModeLeft(或@“left”).因此,当这个层被告知要动画时,它首先看一眼它的内容重力,然后基于随后的动画.因为它看到@“left”,应该有@“resize”,它假定缩放动画应该从左边开始,但它也必须尊重你给它的约束(边界改变),所以你的标签似乎跳入其最终尺寸,然后将其定位在屏幕中央.

如果要离开contentMode,请使用CATransform3D并缩放标签层,而不是边界更改.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...