Lon*_*don 6 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)];
}
Run Code Online (Sandbox Code Playgroud)
这给了我居中的图像,但没用,因为我希望它可以点击,所以我只是用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];
}
Run Code Online (Sandbox Code Playgroud)
我只是想让这个图像可点击以便在点击时执行某种操作,这有多难?
编辑:
我实际上是在实施:
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), (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;
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,UIImageView其属性userInteractionEnabled设置为NO。
做:
[imageView setUserInteractionEnabled:YES];
Run Code Online (Sandbox Code Playgroud)