【问题标题】:Autoresizing frame of UILabel when animating frame (size) of parent UIView动画父 UIView 的框架(大小)时自动调整 UILabel 的框架
【发布时间】:2011-10-27 15:42:20
【问题描述】:

我有一个父 UIView,它有子 UIView(在下面的代码中使用 UILabel),其框架设置为父的边界,其 autoresizingMask 设置为灵活的宽度和高度:

UIView* parentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
UILabel* childLabel = [[UILabel alloc] initWithFrame:parentView.bounds];
childLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
childLabel.textAlignment = UITextAlignmentCenter;
childLabel.text = @"Hello";

我希望能够为父视图的框架设置动画,特别是它的大小,并让子视图调整大小作为动画的一部分:

[UIView animateWithDuration:1.0 animations:^{ parentView.frame = CGRectMake(0, 0, 160, 240); }];

作为这个动画的结果,我希望 UILabel 的文本与父视图的动画一起动画,所以在视觉上你会看到文本从 (160, 240) 的中心移动到 (80, 120) .但是,子视图的帧似乎并没有动画化,而是立即设置为动画结束时应具有的值,因此您会看到动画开始时文本的位置立即跳转。

有没有办法让子视图作为动画的一部分自动调整大小?

【问题讨论】:

    标签: ios cocoa-touch core-animation


    【解决方案1】:

    我并不完全了解发生了什么,但我认为核心问题是 UIKit 不希望在动画的每一帧都重新渲染文本,因此 UILabel 的内容是不是动画的。默认情况下,UILabel 的 contentMode 属性为 UIViewContentModeRedraw,这意味着一旦设置了该属性,它就会以目标大小重绘 UILabel。

    如果将 contentMode 更改为 UIViewContentModeCenter,则内容不会重绘,并且会保持在 UILabel 的中心。

    childLabel.contentMode = UIViewContentModeCenter;
    

    【讨论】:

    • 这是很棒的信息。 UIViewContentModeCenter 适用于我实际需要的内容 - 当父视图的框架缩小或增长时,文本保持居中。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    相关资源
    最近更新 更多