有没有办法动画更改UILabel的textAlignment?

leh*_*058 11 uiviewanimation ios

我正在使用iOS 7,我正在尝试移动一个位于视图左侧中心的标签.目前我试图通过改变我的UILabel的对齐方式来做到这一点,并且我正在尝试在此过程中为其设置动画.我目前正在呼吁以下内容:

[UIView animateWithDuration:0.5
                 animations:^{
                      self.monthLabel.textAlignment = NSTextAlignmentLeft;
                 } completion:nil];
Run Code Online (Sandbox Code Playgroud)

但这只是将标签跳转到新的对齐方式.有没有办法动画这个,或者更好的方法来调整标签以实现这一目标?

bba*_*art 10

将UILabel框架大小设置为精确包含文本并将UILabel置于视图中心.

self.monthLabel.text = @"February";
[self.monthLabel sizeToFit];
self.monthLabel.center = parentView.center; // You may need to adjust the y position
Run Code Online (Sandbox Code Playgroud)

然后设置不应影响布局的对齐,因为没有额外的空间.

self.monthLabel.textAlignment = NSTextAlignmentLeft;
Run Code Online (Sandbox Code Playgroud)

接下来,为UILabel框架大小设置动画,使其滑过您想要的位置.

[UIView animateWithDuration:0.5
             animations:^{
                  CGRect frame = self.monthLabel.frame;
                  frame.origin.x = 10;
                  self.monthLabel.frame = frame;
             } completion:nil];
Run Code Online (Sandbox Code Playgroud)


Som*_*Guy 5

您的标签是多行的吗?像这样的动画:http://img62.imageshack.us/img62/9693/t7hx.png

如果是这样,那么有几个选择。

多行标签

选项1:

尝试使用 UIView 过渡来代替传统的 UIView 动画。文本不会向左滑动,但会很好地淡出到新位置。

[UIView transitionWithView:self.monthLabel
                      duration:0.5
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
        self.monthLabel.textAlignment = NSTextAlignmentLeft;
    } completion:NO];
Run Code Online (Sandbox Code Playgroud)

选项2:

您可以手动确定新行将出现的位置,然后为每行文本创建一个单独的 UILabel,然后对框架进行动画处理。这显然需要更多工作,但会提供所需的幻灯片动画。

单行标签

不要对 textAlignment 进行动画处理,而是使用[self.monthLabel sizeToFit]使标签与其包含的字符串大小相同,然后手动计算出框架和居中。然后只需为框架设置动画,与多行标签上的选项 2 相同。