UIImageView是不能夠響應點擊事件的,在開發過程中我們需要經常對頭像等添加點擊事件,上網搜索一番后發現有如下兩個方法:
1.找到點擊圖片Event,添加事件處理函數
UIImageView.userInteractionEnabled = YES;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
if ([touch view] != UIImageView)
{
//do some method.....
}
}
2.為UIImageView添加Tap手勢
UIImageView.userInteractionEnabled = YES;
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[UIImageView addGestureRecognizer:singleTap];
- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer {
//do something....
}
3.在UIImageView外層套一個UIView,在外層UIView上添加點擊事件處理函數
UIView*view = [[UIControl alloc] initWithFrame:CGRectMake(50,200,150,150)] ; view.backgroundColor = [UIColor clearColor]; [(UIControl *)view addTarget:self action:@selector(xxx) forControlEvents:UIControlEventTouchUpInside]; UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"a.gif"]]; imageView.frame = CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height); [view addSubview:imageView]; [self.view addSubview:view];
ref:http://blog.csdn.net/iorchid/article/details/6398102#
http://www.cocoachina.com/bbs/read.php?tid-66270-page-1.html
