我想通过按钮操作传递一个url,因为我有10个按钮,这些按钮是通过代码动态创建的,然后点击,然后为每个相应的按钮分配一个特定的URL。这是我的代码
NSString *linkUrl = [NSString stringWithFormat:@"%@",[AllrecordG objectForKey:@"Link"]];
[leftLabelG addTarget:self action:@selector(clickMe:linkUrl:) forControlEvents:UIControlEventTouchUpInside];
-(void)clickMe:(UIButton *)sender{
}
但是在这里我收到警告“未使用的变量linkUrl”。
我研究了不同的文章,但有人告诉我不可能通过参数linke。任何人都可以告诉我如何为每个按钮操作传递url以及如何检索这些值。在clickMe定义中。
提前致谢。
答案 0 :(得分: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;
}
答案 1 :(得分:2)
将你的linkurl放在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];
}
答案 2 :(得分: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];
}