TouchsMoved detection inside subview

I am trying to detect touches inside a subview

In my main view controller, I add a subzone called: SideBarForCategory, it takes up 30% of the screen on the left - as a sidebar.

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

      

inside SideBarForCategory, I would like to test 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 (touchsMoved) works fine on the main view (viewcontroller) but doesn't work inside my subheading (SideBarForCategory) - why and how can I fix it?

+3


source to share


2 answers


Two possible solutions I can think of:

  • Use GestureRecognizers (e.g. UITapGestureRecognizer, UISwipeGestureRecognizer) and add these recognizers to the SideBarForCategory view.

  • General gesture handling. Create your own UIView subclass like MyView and add these touch methods to it. Then create the SideBarForCategory view as an instance of MyView.

Hope it works :)

Updated: For the 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 implementation of SideBarCategoryView inside loadView ()

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

      

+1


source


check out Apple links for converting points. You will probably forget to convert the point that belongs to your subzone. So it tries to check the absolute coordinates of the touch point.

You probably need:



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

      

0


source







All Articles