objective-c – 如何使我的图像可点击

前端之家收集整理的这篇文章主要介绍了objective-c – 如何使我的图像可点击前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
显然我很想念UI ImageView和UI Image,为了在图像上注册手势(如点击/点击),我需要在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),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:

今天对此有何看法?

解决方法

您不需要自定义绘图(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),image.size.height)];
    imageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];
    [imageView addGestureRecognizer:tap];

    [self addSubview:imageView];
  }
  return self;
}
原文链接:https://www.f2er.com/c/110698.html

猜你在找的C&C++相关文章