2012-05-14 37 views
5

我想通過按鈕動作傳遞一個url,因爲我有10個按鈕,這些按鈕是通過代碼動態創建的,然後點擊,然後爲每個相應的按鈕分配一個特定的url。這裏是我的代碼我怎樣才能通過UiButton行動中的任何一種參數?

NSString *linkUrl = [NSString stringWithFormat:@"%@",[AllrecordG objectForKey:@"Link"]]; 
[leftLabelG addTarget:self action:@selector(clickMe:linkUrl:) forControlEvents:UIControlEventTouchUpInside]; 

-(void)clickMe:(UIButton *)sender{ 
} 

但是,在這裏我得到警告作爲「未使用的變量linkUrl」。

我已經研究過不同的文章,但有人告訴說,不可能傳遞參數linke。任何人都可以告訴我,如何傳遞每個按鈕操作的url以及如何檢索這些值。在clickMe定義中。

在此先感謝。

回答

11

子類的UIButton這樣的:

MyButton.h

@interface MyButton : UIButton 
{ 
    NSString *_linkUrl; 
} 

@property (nonatomic, retain) NSString *linkUrl 

MyButton.m

@implementation MyButton 
@synthesize linkUrl = _linkUrl 

傳遞linkUrl:

NSString *linkUrl = [NSString stringWithFormat:@"%@",[AllrecordG objectForKey:@"Link"]]; 
[leftLabelG addTarget:self action:@selector(clickMe:) forControlEvents:UIControlEventTouchUpInside]; 
[leftLabelG setLinkUrl:linkUrl]; 

現在你可以得到linkUrl在你的行動那樣:

-(void)clickMe:(MyButton *)sender{ 
     NSString *url = sender.linkUrl; 
} 
+0

能不通過參數動態地通過根據我的要求選擇動作選擇器?像那樣NSString * linkUrl = [NSString stringWithFormat:@「%@」,[AllrecordG objectForKey:@「ColorLink」]]; [leftLabelG addTarget:self action:@selector(clickMe:linkUrl :) forControlEvents:UIControlEventTouchUpInside]; – Banshi

+0

是的,我已經更新了我的回答 – MathieuF

+0

其實我的頁面類已經是@interface homePage:UIViewController 所以我怎樣才能實現你的上述代碼 – Banshi

2

放在一個NSArray中的linkurl;

NSArray *linkUrls = [NSArray arratWithObjects:@"link",@"blah",@"blah"........,nil]; 

然後設置一個標記您的按鈕作爲數組索引,然後

leftLabelG.tag = 1; 
rightLabelG.tag = 2; 

-(void)clickMe:(UIButton *)sender{ 
     NSString *url = [linkUrls objectAtIndex:sender.tag]; 
} 
0

使用類別

- (void)addTarget:(id)target action:(SEL)action withObject:(id)object forControlEvents:(UIControlEvents)controlEvents; 


-(void)addTarget:(id)target action:(SEL)action withObject:(id)object1 withObject:(id)object2 forControlEvents:(UIControlEvents)controlEvents { 
SEL action_ = [self generateAction:action withObject:object1 withObject:object2]; 
IMP impl = imp_implementationWithBlock(^(id self_) { 
    objc_msgSend(self_, action, self, [object1 copy], [object2 copy]); 
}); 
class_replaceMethod([target class], action_, impl, "[email protected]:@"); 

[self addTarget:target action:action_ forControlEvents:controlEvents]; 

}