我正在尝试检测 subview 内的触摸
在我的主视图 Controller 中,我添加了一个名为:SideBarForCategory 的 subview ,它占据了屏幕左侧的 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) 上完美运行,但在我的 subview (SideBarForCategory) 中不起作用 - 为什么以及如何修复它?
最佳答案
我能想到的两种可能的解决方案:
使用 GestureRecognizers(例如 UITapGestureRecognizer、UISwipeGestureRecognizer)并将这些识别器添加到您的 SideBarForCategory View 。
通用手势处理:创建您自己的 UIView 自定义子类(例如 MyView)并在其中添加这些触摸方法。然后创建 SideBarForCategory View 作为 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];
关于iphone - subview 内的 touchesMoved 检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9667552/