由无法识别的选择器导致的NSInvalidArgumentFormatException被发送到发件人:尝试打印UILabel的标签时

时间:2014-01-07 07:21:16

标签: ios objective-c

我有一个ScrollView,它有很多数据块。每个块都有一个UILabel。我正在for循环中创建每个块:

for(int i = 0 ; i < x ; i++){

        UILabel *claim = [[UILabel alloc]initWithFrame:CGRectMake(40,135, self.view.bounds.size.width, 30)];
        claim.text = @"claim";
        [claim setTag:i];
        NSLog(@"%ld",claim.tag);
        claim.font = [UIFont fontWithName:@"Arial" size:(20.0)];
        [claim setTextColor:[UIColor purpleColor]];

        //create a tab recogniser for claim text
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                       initWithTarget:self
                                               action:@selector(claimClicked:)];
        [claim setUserInteractionEnabled:YES];
        [claim addGestureRecognizer:tap];
        [scrollView addSubView :claim];
}
[self.view addSubView : scrollView];

声明标签的选择器是:

- (IBAction)claimClicked:(UILabel *)sender{
    NSInteger the_tag = ((UIView*)sender).tag;
    NSLog(@"%ld",the_tag);
}

基本上我只是在点击标签时打印标签。但我得到一个例外说:

在NSlog行上

NSInvalidArgumentFormatException caused by unrecognized selector was sent to sender

帮助。

2 个答案:

答案 0 :(得分:3)

实际上这里的发件人是UITapGestureRecognizer。

改为使用代码:

- (IBAction)claimClicked:(UIGestureRecognizer *)sender
{
    NSLog(@"%d",sender.view.tag);
}

答案 1 :(得分:1)

你不能做这个定义- (IBAction)claimClicked:(UILabel *)sender。因为根据此行UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(claimClicked:)];,您的发件人为UITapGestureRecognizer.

相反试试这个..

- (IBAction)claimClicked:(UIGestureRecognizer *)sender
{
   if([sender.view isKindOfClass:[UILabel class]])
      NSLog(@"Label tag %d",sender.view.tag);
}