如何在多个视图中重用相同的UIButton

时间:2012-09-29 00:15:22

标签: ios uibutton

我创建了一个这样的按钮:

UIButton *toTop = [UIButton buttonWithType:UIButtonTypeCustom];
toTop.frame = CGRectMake(12, 12, 37, 38);
toTop.tintColor = [UIColor clearColor];
[toTop setBackgroundImage:[UIImage imageNamed:@"toTop.png"] forState:UIControlStateNormal];
[toTop addTarget:self action:@selector(scrollToTop:) forControlEvents:UIControlEventTouchUpInside];

我有各种UIViews,我想一遍又一遍地使用同一个按钮,但我不能这样做。我尝试将相同的UIButton添加到多个视图中,但它总是出现在我添加它的最后一个位置。我也试过了:

UIButton *toTop2 = [[UIButton alloc] init];
toTop2 = toTop;

哪个不起作用。有没有一种有效的方法来做到这一点,而不是一遍又一遍地为同一个按钮设置所有相同的属性?感谢。

1 个答案:

答案 0 :(得分:2)

UIView s只能拥有一个超级视图。使用第二种方法,您只需分配一个按钮,然后将其丢弃并指定其指针指向第一个按钮。所以现在toToptoTop2都指向完全相同的按钮实例,并且您回到单个超级视图限制。

因此,您需要创建单独的UIButton实例来完成此任务。在不重复代码的情况下执行此操作的一种方法是编写类别。这样的事情应该有效:

的UIButton + ToTopAdditions.h:

@interface UIButton (ToTopAdditions)

+ (UIButton *)toTopButtonWithTarget:(id)target;

@end

的UIButton + ToTopAdditions.m:

@implementation UIButton (ToTopAdditions)

+ (UIButton *)toTopButtonWithTarget:(id)target
{
    UIButton *toTop = [UIButton buttonWithType:UIButtonTypeCustom];
    toTop.frame = CGRectMake(12, 12, 37, 38);
    toTop.tintColor = [UIColor clearColor];
    [toTop setBackgroundImage:[UIImage imageNamed:@"toTop.png"] forState:UIControlStateNormal];
    [toTop addTarget:target action:@selector(scrollToTop:) forControlEvents:UIControlEventTouchUpInside];
    return toTop;
}

@end

导入UIButton+ToTopAdditions.h,将相应的目标传递给方法(在您的情况下听起来像self),您将获得所需数量相同的按钮。希望这有帮助!

相关问题