UILabel动画不正常。

3
由于某些原因,UILabel的文本想要在没有动画的情况下设置其对齐方式,我无法弄清如何使文本与标签的其余部分一起动画。
我目前的代码如下:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40,200,100,50)];
[label setText:@"Label Name"];
[label setBackgroundColor:[UIColor blueColor]];
[label setFont:[UIFont systemFontOfSize:17.0]];
[label setTextColor:[UIColor blackColor]];
[label setTextAlignment:NSTextAlignmentCenter];
[self.view addSubview:label];
[UIView animateWithDuration:3 animations:^{
    [label setFrame:CGRectMake(40,200,200,300)];
}];

在一个按钮的动作方法中调用此代码。通常,动画将与标签的创建分开进行,但我将其放在同一方法中进行测试。

出于某种原因,当运行此代码时,该标签会按预期完美地调整大小,并且我可以看到帧进行调整。但是,文本在水平轴上自我对齐到动画结束时的位置。然而,在垂直轴上,它会正确地进行动画。

目前,动画如下所示:

animate1 animate2 animate3

由于某种原因,标签的文本在上下移动时保持居中,但在左右移动时不保持居中,这不是我所预期的。

我已经搜索了很多地方,但没有找到解决方案。有人知道UILabel为什么会这样行事吗?是否有任何解决方法?


可能并不像我们想象的那样简单。但是请在这里查看:https://dev59.com/VmYq5IYBdhLWcg3wbgDk?rq=1 。我很快就会尝试一下,并告诉你我是否解决了它。 - Petar
谢谢!我不喜欢使用比例变换,但我想我没有看到更好的方法来做到这一点。 - Jsdodgers
1个回答

1
您可以添加一个UIView,然后将UILabel作为其子视图添加:
 UIView *view = [[UIView alloc] initWithFrame:CGRectMake(40, 20, 100, 50)];
[view setBackgroundColor:[UIColor blueColor]];
[self.view addSubview:view];

UILabel *label = [[UILabel alloc] init];
[label setText:@"Label Name"];
[label setBackgroundColor:[UIColor clearColor]];
[label setFont:[UIFont systemFontOfSize:17.0]];
[label setTextColor:[UIColor blackColor]];
[label setTextAlignment:NSTextAlignmentCenter];
[label sizeToFit];
[label setNumberOfLines:0];
[label setFrame:CGRectOffset(label.frame, (view.frame.size.width - label.frame.size.width)/2, (view.frame.size.height - label.frame.size.height)/2)];
[view addSubview:label];

 [UIView animateWithDuration:3 animations:^{
 [view setFrame:CGRectMake(40, 20, 200, 300)];
 [label setFrame:CGRectMake((view.frame.size.width - label.frame.size.width)/2, (view.frame.size.height - label.frame.size.height)/2, label.frame.size.width, label.frame.size.height)];
 } completion:^(BOOL finish){

 }];

好的,我明白了。我猜只有改变宽度才会这样做,而不是移动框架。 - Jsdodgers
在上面的代码中,我所做的只是将UILabel添加到UIView作为其子视图,然后根据UIView更改其xy坐标。 - Burhanuddin Sunelwala

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接