如何使我的图像可点击

时间:2012-02-28 21:54:09

标签: objective-c ios ios5

显然我很想念UIImageView和UIImage,为了在图像上注册手势(如点击/点击),我需要在uiimageview中有图像并在uiimageview上注册手势而不是在uiimage上。

所以这段代码对我有用:

- (void)drawRect:(CGRect)rect {    
    Obj *obj = ... obj has imageHref which is NSString

    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:obj.imageHref]]; 
    [image drawInRect:CGRectMake((self.frame.size.width/2) - (image.size.with/2), (self.frame.size.height / 2) - (image.size.height / 2), image.size.width, image.size.height)];

}

这给了我居中的图像,但没用,因为我希望它可以点击,所以我只是用UIImageview来做这样的:

  - (void)drawRect:(CGRect)rect {    
            Obj *obj = ... obj has imageHref which is NSString

            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:obj.imageHref]]; 

    CGRect rect1=CGRectMake((self.frame.size.width/2) - (image.size.width/2), (self.frame.size.height / 2) - (image.size.height / 2), image.size.width, image.size.height);

    UIImageView *backgroundImageView = [[UIImageView alloc] initWithImage:radioStationImage];

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];

    [backgroundImageView addGestureRecognizer:tap];

            [backgroundImageView drawRect:rect1];

        }

我只是想点击这个图片点击进行某种动作,这有多难?

编辑:

我实际上是在实施:

https://github.com/andreyvit/SoloComponents-iOS/tree/master/ATPagingView

哪个提供整洁的页面滚动。但是屏幕中间的可点击图像不是第1页,第2页等。

编辑2:

今天对此有何看法?

2 个答案:

答案 0 :(得分:8)

您不需要自定义绘图(drawRect:)。只需在加载视图时将UIImageView添加为子视图(在Interface Builder中或loadView中,具体取决于您初始化视图的方式)。然后,您可以在执行时将UITapGestureRecognizer添加到该视图。

正如@jackslash所说,你还需要在完成后启用图像视图的用户交互。


我相信你做的比现在复杂得多。无需使用drawRect:进行自定义绘图。不需要子类化UIImageView(链接@ madmik3引用与iOS4 +无关)。可能不需要实际的UIView子类(您可以在视图控制器中执行所有这些操作),但是这里是如何在视图子类中执行此操作:

- (id)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    Obj *obj = ... obj has imageHref which is NSString
    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:obj.imageHref]]; 
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((self.frame.size.width/2) - (image.size.with/2), (self.frame.size.height / 2) - (image.size.height / 2), image.size.width, image.size.height)];
    imageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];
    [imageView addGestureRecognizer:tap];

    [self addSubview:imageView];
  }
  return self;
}

答案 1 :(得分:2)

默认情况下,UIImageView将其属性userInteractionEnabled设置为NO

做的:

[imageView setUserInteractionEnabled:YES];