【问题标题】:Swift - How to check if a CAShapeLayer intersects with a button (UIView)?Swift - 如何检查 CAShapeLayer 是否与按钮(UIView)相交?
【发布时间】:2021-05-31 16:29:33
【问题描述】:

如标题所述,我无法检查按钮是否与 CAShapeLayer 相交。现在我有一个通过 UIPanGestureRecognizer 移动的按钮。当它放开时,我想检查它是否在我拥有的这个轮子上的某种颜色之上: Simulator View

颜色被生成为 CAShapeLayers,代码如下:

let path1 = UIBezierPath()
path1.addArc(withCenter: center, radius: 50, startAngle: CGFloat.pi/4 + 0.1, endAngle: CGFloat.pi*3/4 - 0.1, clockwise: true)
path1.addArc(withCenter: center, radius: 125, startAngle: CGFloat.pi*3/4 - 0.05, endAngle: CGFloat.pi/4 + 0.05, clockwise: false)
blueCircle.path = path1.cgPath
blueCircle.fillColor = UIColor(red: 0, green: 143/255, blue: 208/255, alpha: 1).cgColor
self.view.layer.addSublayer(blueCircle)

其中 blueCircle 是 CAShapeLayer。

我有代码检查我的“识别器”(UIPanGestureRecognizer)是否在发布时重叠,看起来像这样:

   if recognizer.view!.frame.intersects(blueCircle.frame) {
       print("Blue overlap")
   }

但我怀疑它总是返回 false,因为它们不在同一个“层”中。我尝试了各种方法,包括使用边界而不是框架以及尝试使用手势识别器的中心进行转换,但它似乎无法正常工作。

【问题讨论】:

  • 你说的按钮是recognizer.view!吗?还是self.view
  • @Sweeper Recognizer.view!是按钮

标签: ios swift uiview uigesturerecognizer cashapelayer


【解决方案1】:

你需要检查与主视图相交(self.view)

你也可以试试这个

- (BOOL)checkViewIntersectsWithAnotherView:(UIView*)selectedView {

    NSArray *subViewsInView = [self.view subviews];// I assume self is a subclass
                                       // of UIViewController but the view can be
                                       //any UIView that'd act as a container 
                                       //for all other views.

     for(UIView *theView in subViewsInView) {

       if (![selectedView isEqual:theView])
           if(CGRectIntersectsRect(selectedView.frame, theView.frame))  
              return YES;
    }

  return NO;
}

【讨论】:

  • 我看不出这会有什么帮助。 CAShapeLayers 不是视图,所以无论如何我都无法使用它调用此函数
【解决方案2】:

因此,对于遇到此问题的任何人,我都设法找到了解决方案。似乎您可以在 CAShapeLayers 上调用框架,但是当我检查打印输出时,它给了我“(0,0,0,0)”。我最终用

替换了调用框架的代码
if self.view.intersects((blueCircle.path?.boundingBox)!) {
    print("Blue overlap")
}

所以我正在寻找路径,这非常有效。

【讨论】:

    猜你喜欢
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    相关资源
    最近更新 更多