2012-09-29 103 views
0

我創建像這樣一個按鈕:如何重複使用相同的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; 

哪個不行。有沒有一種有效的方法來做到這一點,而不是一次又一次地爲同一個按鈕設置所有相同的屬性?謝謝。

回答

2

UIView s只能有一個superview。使用第二種方法,您只需分配一個按鈕,然後將其丟棄並將其指針指向指向第一個按鈕。所以現在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),並且你會得到儘可能多的相同的按鈕。希望這可以幫助!

相關問題