如何从ios中的UIImageViiew获取标签?

时间:2015-10-29 04:59:44

标签: ios objective-c uiimageview

我在UIImageView添加了点按手势。当我点击图像时,我想从中获取标签。请告诉我怎么办?

UITapGestureRecognizer *tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tap_post_image:)];

tapGesture1.numberOfTapsRequired = 1
[tapGesture1 setDelegate:self];
[cell.beizer_image setUserInteractionEnabled:true];
[cell.beizer_image addGestureRecognizer:tapGesture1];
[cell.beizer_image setTag:indexPath.row];

- (void) tap_post_image: (id)sender
{
    NSInteger the_tag = ((UIView*)sender).tag;
    NSLog(@"tap post image is called");
    NSLog(@"TAG is %ld",(long)the_tag);
}

上面的代码崩溃了应用程序。

2 个答案:

答案 0 :(得分:4)

虽然您确实需要提供问题详情,但一个明显的问题是您认为sender方法的top_post_image:参数是UIView

这是不正确的。参数将是手势识别器,而不是视图。但你可以从手势中获得视图。

代码应为:

- (void)tap_post_image:(UITapGestureRecognizer *)gesture {
    NSInteger the_tag = gesture.view.tag;
}

在不相关的说明中,您需要处理命名约定。在Objective-C(以及许多其他语言)中,通常的做法是使用所谓的"驼峰案例'。您的方法应命名为tapPostImage:,而不是tap_post_image

答案 1 :(得分:0)

您将崩溃,因为代码中的发件人不是uiview,uiimageview。 sender是UITapGestureRecognizer类。 你应该做

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapImageView:)];
    [tapGesture setNumberOfTapsRequired:1];
    [self.sampleImage setUserInteractionEnabled:YES];
    [self.sampleImage addGestureRecognizer:tapGesture];
    [self.sampleImage setTag:99];

    - (void)tapImageView:(id)sender {
        NSLog(@"Sender is a %@ class",NSStringFromClass([sender class]));
        UITapGestureRecognizer *tapGesture = ((UITapGestureRecognizer *)sender);
        UIImageView *imageView = (UIImageView *)tapGesture.view;
        NSLog(@"imageView.tag = %d",imageView.tag);
    }

我希望它有所帮助!