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

Iphone 适应多种对象类型的方法?,iphone,objective-c,ipad,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 commi

我有这样一种方法,可以让我转换对象的位置,在iPhone应用程序中为其移动设置动画:

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

您可以看到此方法适用于
UILabels
,但是没有此方法的副本(只需将对象替换为
UIButton
),我是否可以调整此方法,以便传递任何带有帧的对象?每个对象类型都不需要单独的方法。

UIView
中,
UILabel
UIButton
都有一个共同的祖先;尝试将其传递到
标签
(您似乎只修改标签的
属性,该属性在
UIView
中定义)。

您还可以使用动画移动方法为
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
现在您只需调用
[按钮设置帧:新帧动画:是]
[标签设置帧:新帧动画:是]