2012-01-09 39 views
1

所以我有一个UIView对象(称为标尺)在右侧是一个垂直条。我在该栏左侧有另一个标签,我想在垂直栏的不同层级显示不同的文本(navLabel)。我希望这个标签看起来像被固定到我的垂直条的某个距离(如10像素)。我的标签是左对齐的。我这样做,在我需要更新的标签不同的方法:参考另一个UIView对象的UILabel动画

 CGSize labelSize = [navLabel.text sizeWithFont:[UIFont fontWithName:@"Arial" size:17.0]]; 
     CGRect newFrame = CGRectMake(gauge.frame.origin.x - 10 - labelSize.width, FIRST_HEIGHT, navLabel.frame.size.width, navLabel.frame.size.height); 
     [UIView animateWithDuration:0.5 animations:^{ 
      self.navLabel.frame = newFrame; 
     }]; 

在我不同的方法,我只是切换到适当的高度(即#define FIRST_HEIGHT)。

我的标签结束了我想要的地方,但动画看起来很有趣。例如,如果我的第一个标签是@"label 1",而我的第二个标签是@"my much much much longer label",会发生什么情况是标签达到了正确的高度,但由于标签的尺寸不同,因此您会看到x-animation,这使其看起来很有趣。我只想在y方向上进行动画。我怎么能做到这一点?

我也试过右对齐,但后来我的标签没有结束与我的量表对象的正确距离。它结束了很多次,我不知道为什么会发生这种情况。

回答

0

目前尚不清楚,这是你想要的行为,但为什么不直接设置navLabel.frame有正确的(新)为原点生动活泼的x坐标,然后进行动画到具有正确的起源新框架与新的高度抵消?

或者,使用这两个框架设置两个动画,一个动画化第一个y方向,第二个动画化x方向到帧原点的新x坐标。或相反亦然。

// This version simply sets the correct origin (and the correct new width), then animates the y-direction 
CGSize labelSize = [navLabel.text sizeWithFont:[UIFont fontWithName:@"Arial" size:17.0]]; 
self.navLabel.frame = CGRectMake(gauge.frame.origin.x-10-labelSize.width, self.navLabel.frame.origin.y,labelSize.width,navLabel.frame.size.height); 
// now navLabel's frame has the correct new width (and origin x-coord) 
CGRect newFrame = CGRectMake(self.navLabel.origin.x, FIRST_HEIGHT, navLabel.frame.size.width, navLabel.frame.size.height); 
// now this animation will cause movement only in the y-direction 
[UIView animateWithDuration:0.5 animations:^{ 
     self.navLabel.frame = newFrame; 
    }]; 

// This version animates the change in the frame in the x-direction first, then does what it did before 
CGSize labelSize = [navLabel.text sizeWithFont:[UIFont fontWithName:@"Arial" size:17.0]]; 
CGRect newFrame = CGRectMake(gauge.frame.origin.x-10-labelSize.width, self.navLabel.frame.origin.y,labelSize.width,navLabel.frame.size.height); 
// this animation will cause movement in the x-direction 
[UIView animateWithDuration:0.5 animations:^{ 
     self.navLabel.frame = newFrame; 
    }]; 
// now navLabel's frame has the correct new width (and origin x-coord), so set the new y-coord 
CGRect newFrame = CGRectMake(self.navLabel.origin.x, FIRST_HEIGHT, navLabel.frame.size.width, navLabel.frame.size.height); 
// now this animation will cause movement only in the y-direction 
[UIView animateWithDuration:0.5 animations:^{ 
     self.navLabel.frame = newFrame; 
    }]; 
+0

如何为y坐标或x坐标生成动画?创建一个只更改了该值的框架,然后在我的UIView动画块中设置新框架?谢谢。 – Crystal 2012-01-09 20:45:59

+0

是的,确切地说。如果你的框架之间的差异只是这些坐标中的一个*,那么这就是动画。但是,只需在动画之前或之后设置框架以将更新后的x坐标作为原点,也可能使其看起来很有趣,因此您可能必须仔细研究行为以获得对您来说看起来不错的东西。或者,正如我所建议的那样,您可以为一个“方向”和另一个“方向”制作动画。查看我更新的答案以获取代码示例。 – ddodev 2012-01-09 20:48:58