【问题标题】:Touch events does not get called in UIView class iOS Objective c在 UIView 类 iOS 目标 c 中未调用触摸事件
【发布时间】:2023-03-05 05:05:01
【问题描述】:

我已经使用下面的代码从我的主视图控制器中编写了一个动态视图

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];

现在我正在尝试使用下面的 sn-ps 从我的 UIView 类中获取触摸事件

    -(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 方法没有被调用,我哪里出错了。任何帮助都会很棒...

【问题讨论】:

  • 显示ViewClass的init方法
  • ViewClass中没有init方法
  • ViewClass *View 是局部变量吗?
  • 不......它的 obj 用于 UIView 类

标签: ios uiview touchesbegan touchesmoved touch-event


【解决方案1】:

这个答案将有助于迅速

在 ViewDidLoad 中为 yourCustomView 启用 userInteraction

 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 2011-05-16
    • 2021-02-09
    • 2010-12-02
    • 2010-11-10
    • 1970-01-01
    相关资源
    最近更新 更多