我正在尝试检测子视图中的触摸
在我的主视图控制器中,我添加一个名为:SideBarForCategory的子视图,它从左侧占据屏幕的30% - 作为侧边栏。
SideBarForCategory *sideBarForCategory = [[SideBarForCategory alloc] initWithNibName:@"SideBarForCategory" bundle:nil];
[sideBarData addSubview:sideBarForCategory.view];
在SideBarForCategory中,我想测试触摸
-(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);
}
上面的代码(touchesMoved)在主视图(viewcontroller)上完美运行,但在我的子视图中不起作用(SideBarForCategory) - 为什么以及如何修复?
答案 0 :(得分:1)
我能想到的两种可能的解决方案:
使用GestureRecognizers(例如UITapGestureRecognizer,UISwipeGestureRecognizer)并将这些识别器添加到SideBarForCategory视图中。
通用手势处理:创建您自己的UIView自定义子类,例如MyView,并在其中添加这些触摸方法。然后创建SideBarForCategory视图作为MyView的实例。
希望它有效:)
更新: 第二种选择:
#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
更新: 然后在你的SideBarCategoryView类实现中,在loadView()
里面self.view = [[MyView alloc] init];
答案 1 :(得分:0)
查看Apple转换积分的参考资料。您可能忘记转换与子视图相关的点。因此,它试图检查触摸点的绝对坐标。
您可能需要的是:
- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view