iphone - subview 内的 touchesMoved 检测

标签 iphone objective-c ios ipad touch

我正在尝试检测 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) 中不起作用 - 为什么以及如何修复它

最佳答案

我能想到的两种可能的解决方案:

  1. 使用 GestureRecognizers(例如 UITapGestureRecognizer、UISwipeGestureRecognizer)并将这些识别器添加到您的 SideBarForCategory View 。

  2. 通用手势处理:创建您自己的 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/

相关文章:

objective-c - 在 iOS objective-c 中将 iPhone 属性设置为只读

ios - 1个按钮,播放10个声音?

javascript - 重新格式化为横向 View

iphone - 是否可以使用 Xcode 4 为 IOS 4.0 编译 iPhone 应用程序

c++ - 如何为 ios 应用程序构建和使用 C++ 静态库

ios - 主队列中将 CIImage 转换为 CGImage 时发生泄漏

ios - iOS应用图片分辨率

iphone - 使用 tableview 作为 uitextview

ios - 如何在 iphone 5 和 iphone 6 上更改 ImageView 的大小?

iOS - 表格 View 单元格无法正确呈现