UILabel动画引用另一个UIView对象

时间:2012-01-09 19:48:22

标签: iphone uiview

所以我在右侧有一个UIView对象(称为gauge),它是一个垂直条。我在该栏左侧有另一个标签,我想在垂直栏的不同级别(navLabel)显示不同的文字。我希望这个标签看起来像是固定在我垂直条的某个距离(比如10像素)。我的标签是左对齐的。我在需要更新标签的不同方法中执行此操作:

        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动画这也让它看起来很有趣。我只想要y方向的动画。我怎么能做到这一点?

我也尝试过右对齐,但是我的标签没有达到我的仪表对象的正确距离。它最终越过它多次,我不知道为什么会发生这种情况。

1 个答案:

答案 0 :(得分: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;
    }];