适应多种对象类型的方法?

时间:2012-07-05 15:39:10

标签: iphone objective-c ipad

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

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

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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]