UILabel 动画不正确 [英] UILabel animating improperly

查看:29
本文介绍了UILabel 动画不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,UILabel 的文本想要在没有动画的情况下设置其对齐方式,我无法弄清楚如何让文本与标签的其余部分一起动画.

For some reason, UILabel's text wants to set its alignment without animation, and I cannot figure out how to get the text to animate along with the rest of the label.

我现在有以下代码:

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)];
}];

此代码在按钮的操作方法中调用.通常动画会与标签的创建分开发生,但我把它放在相同的方法中进行测试.

This code is called in a button's action method. Normally the animation will happen separately from the creation of the label but I put it in the same method to test it.

出于某种原因,当它运行时,标签完全按照预期调整大小,我可以看到框架调整大小.但是,文本在水平轴上与动画结束时的位置对齐.然而,在垂直轴上,它的动画效果很好.

For some reason when this runs, the label gets resized perfectly as it is supposed to and I can see the frame resize. However, the text aligns itself in the horizontal axis to the position that it will be at at the end of the animation. In the vertical axis, however, it animates properly.

现在这是动画的样子:

出于某种原因,标签的文本在上下移动时会保持居中,但不会像我认为的那样保持左右居中.

For some reason, the label's text stays centered when moving up and down but it does not stay centered left-right, as I would assume it should.

我已经找遍了,找不到解决方案.有谁知道 UILabels 的行为是这样的,是否有任何解决方法?

Ive looked all over and couldn't find a solution to this. Does anyone know what UILabels behave like this and if there is any way around it?

推荐答案

您可以添加一个 UIView,然后添加 UILabel 作为其子视图:

You could add an UIView and then add UILabel as its subview:

 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){

 }];

这篇关于UILabel 动画不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆