UILabel animating improperly

↘锁芯ラ 提交于 2019-12-12 14:15:16

问题


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.

I have the following code right now:

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.

Right now this is what the animation looks like:

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.

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?


回答1:


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

 }];


来源:https://stackoverflow.com/questions/15534022/uilabel-animating-improperly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!