5

I want to pass a url through button action, because i have 10 buttons which are created through code dynamically and on clicking then there a specific url are assign for each corresponding button. Here is my code

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

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

But here I get warning as "unused variable linkUrl".

I have studied different articles but somebody told that it is not possible to pass argument linke that. Anybody can tell me that how can i pass url for each button action and also how I retrieve those values. in the clickMe definition.

Thanks in advance.

4

3 回答 3

11

子类 UIButton 像这样:

我的按钮.h

@interface MyButton : UIButton
{
     NSString *_linkUrl;
}

@property (nonatomic, retain) NSString *linkUrl

我的按钮.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;
}
于 2012-05-14T08:13:44.693 回答
2

将您的链接网址放在 NSArray 中;

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

然后为您的按钮设置一个标签作为数组中的索引,然后

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

-(void)clickMe:(UIButton *)sender{
      NSString *url = [linkUrls objectAtIndex:sender.tag];
}
于 2012-05-14T08:26:10.930 回答
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, "v@:@");

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

}

于 2015-05-10T16:18:56.843 回答