在 UIView 中不调用触摸事件 class iOS Objective c

Touch events does not get called in UIView class iOS Objective c

我使用下面的代码

从我的主 viewcontroller 编写了一个动态视图
ViewClass *View;

   View = [[ViewClass alloc] initWithFrame:CGRectMake(70, 100, 200, 200)];
   View.layer.cornerRadius = View.frame.size.width/2;
   View.layer.masksToBounds = YES;
   View.backgroundColor = [UIColor clearColor];
   View.userInteractionEnabled = YES;
   [self.view addSubview:View];

现在我正在尝试使用以下代码片段从我的 UIView class 获取触摸事件

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {

    [super touchesBegan:touches withEvent:event];

    UITouch *touch = [touches anyObject];
    locationOfTouch = [touch locationInView:self];
}

    - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{

    [super touchesMoved:touches withEvent:event];

    UITouch *touch = [[event allTouches] anyObject];
    locationOfTouch = [touch locationInView:self];
}

但是没有调用 touchesBegan 方法,我哪里出错了。任何帮助都会很棒...

这个答案将有助于swift

在 ViewDidLoad 中为您的自定义视图启用用户交互

 yourCustomView.userInteractionEnabled = true

调用这个方法

 override func touchesBegan(touches: Set, withEvent event: UIEvent) {

     super.touchesBegan(touches, withEvent: event)

     let touch: UITouch = touches.first as! UITouch

     if (touch.view == yourCustomView){
     print("touchesBegan | This is an yourCustomView")
     }else{
     print("touchesBegan | This is not an yourCustomView")
     }

  }

希望这会有所帮助..! :D