开发者

How to detect touch on UIImageView inside UIScrollview?

I have a UIScrollview in my app and I populate it with LOTS of UIImageViews approx 900. They are all very small and consist of only two different images over and over again.

Now I am having a lot of trouble detecting a touch on one of these UIImageViews.

I have assigned them all a unique TAG so as to be able to distinguish between them but I am really struggling to detect the touch.

The goal is just to be able to change the image of the touched UIImageView.

Due to the large amount of views involved a simple loop checking touch coordinates against each UIImageViews frame is just hanging my app.

Does anyone have any suggesti开发者_运维问答ons?

Thanks in Advance.

Ben


In my case the easiest way to do it was adding a gesture recognizer:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
//Default value for cancelsTouchesInView is YES, which will prevent buttons to be clicked
singleTap.cancelsTouchesInView = NO; 
[myScrollView addGestureRecognizer:singleTap];   

Then use this method to capture the touch:

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
  { 
    CGPoint touchPoint=[gesture locationInView:myScrollView];
  }


UIImageView has touch processing turned off by default. To change that set userInteractionEnabled to YES (see the docs here http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIImageView_Class/Reference/Reference.html)

Also if you want to know which view was hit in a view hierarchy you can use hitTest:withEvent: (see docs in UIView) which will be much faster than you looping through the hierarchy.

On a wider note I don't think having 900 UIImageView's on the screen all at once is going to be a good long term strategy. Have you investigated drawing the screen's content via CoreGraphics?


The best way to solve this issue is to subclass UIScrollView, add touchesBegan etc methods to it.

@interface MyScroll : UIScrollView
 {

 }


You could easily implement this method on the UIImageView object:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if ([self pointInside:point withEvent:event]) {
      //You clicked inside the object
    }
    return [super hitTest:point withEvent:event]
}

Use the return to tell the application the next touch responder (such as the uiimageview or the scrollview).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜