iOS開發-UIImageView響應點選事件
阿新 • • 發佈:2019-02-04
UIImageView是不能夠響應點選事件的,在開發過程中我們需要經常對頭像等新增點選事件,上網搜尋一番後發現有如下兩個方法:
1.找到點選圖片Event,新增事件處理函式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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手勢
1 2 3 4 5 6 7 8 9 |
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上新增點選事件處理函式
1 2 3 4 5 6 7 |
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