1

我有这个方法可以让我翻译一个对象的位置,在我的 iPhone 应用程序中动画它的移动:

-(void)translatePositionForLabel:(UILabel *)label toFrame:(CGRect)newFrame
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    label.frame = newFrame;
    [UIView commitAnimations];
}

您可以看到这适用于UILabels,但是没有此方法的副本(只是将对象交换为 say UIButton),无论如何我可以调整此方法,以便可以通过框架传递任何对象吗?而不是每个对象类型都需要一个单独的方法。

4

2 回答 2

2

两者UILabel都有UIButton共同的祖先UIView;尝试传递它来代替label(您似乎只修改了标签的frame属性,该属性在 中定义UIView)。

于 2012-07-05T15:44:34.577 回答
1

您还可以为UIView使用动画移动的方法创建一个类别:

UIView+Additions.h

@interface UIView (Additions)

- (void)setFrame:(CGRect)frame animated:(BOOL)animated;

- (void)translateToPoint:(CGPoint)point animated:(BOOL)animated;

@end

UIView+Additions.m

@implementation UIView (Additions)

- (void)setFrame:(CGRect)newFrame animated:(BOOL)animated {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    self.frame = newFrame;
    [UIView commitAnimations];
}

- (void)translateToPoint:(CGPoint)point animated:(BOOL)animated {
    CGRect newFrame = self.frame;
    newFrame.origin = point;
    [self setFrame:newFrame animated:animated];
}

@end

现在您可以调用[button setFrame:newFrame animated:YES][label setFrame:newFrame animated:YES]

于 2012-07-05T16:00:04.243 回答