chewy
chewy

Reputation: 8267

touchesMoved detection inside a subview

I am trying to detect touches inside a subview

In my main viewcontroller I am adding a subview called:SideBarForCategory, it takes 30% of the screen from the left - as a sidebar.

SideBarForCategory *sideBarForCategory = [[SideBarForCategory alloc] initWithNibName:@"SideBarForCategory" bundle:nil];  
[sideBarData addSubview:sideBarForCategory.view];

inside SideBarForCategory, I would like to test for touches

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event touchesForView:self.view] anyObject];

    CGPoint location = [touch locationInView:touch.view];
    NSLog(@"Map Touch %f",location.x);

}

The above code (touchesMoved) works perfectly on the main view (viewcontroller) but does not work inside my subview (SideBarForCategory) - why and how can I fix it?

Upvotes: 3

Views: 1950

Answers (2)

Yatin Sarbalia
Yatin Sarbalia

Reputation: 209

Two possible solutions i can think of :

  1. Either use GestureRecognizers (eg. UITapGestureRecognizer, UISwipeGestureRecognizer) and add those recognizers to your SideBarForCategory view.

  2. Generic gesture handling : Create your own custom subclass of UIView for example MyView and add those touch methods inside it. Then create SideBarForCategory view as an instance of MyView.

Hope it works :)

Updated : For second option :

#import <UIKit/UIKit.h>

@interface MyView : UIView
@end





@implementation MyView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  // No need to invoke |touchesBegan| on super
  NSLog(@"touchesBegan");
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  // invoke |touchesMoved| on super so that scrolling can be handled
  [super touchesMoved:touches withEvent:event];
  NSLog(@"touchesMoved");
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  [super touchesEnded:touches withEvent:event];
  NSLog(@"touchesEnded");
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
  /* no state to clean up, so null implementation */
  NSLog(@"touchesCancelled");
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end

Update : And then in your SideBarCategoryView class implementation , inside loadView()

self.view = [[MyView alloc] init];

Upvotes: 1

Ugur Kumru
Ugur Kumru

Reputation: 986

check Apple's references for converting points. You probably forget to convert the point relevant to your subview. Therefore it is trying to check the absolute coordinates of the touch point.

Probably what you need is :

- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view

Upvotes: 1

Related Questions