因此,我绘制了许多CAShapeLayers,在我的touchesBegan函数中,当这些层之一被触摸时,我想执行一个操作。
我绘制图层的方法之一是:
func drawBoundary(line: UIBezierPath) {
let boundaryLayer = CAShapeLayer()
boundaryLayer.lineCap = .square
boundaryLayer.path = line.cgPath
boundaryLayer.strokeColor = UIColor.green.cgColor
boundaryLayer.lineWidth = 100
boundaryLayer.opacity = 0.2
boundaryLayer.accessibilityLabel = "OuterBoundary"
self.layer.addSublayer(boundaryLayer)
}
touchedBegan函数:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let point = touch!.location(in: self)
print(point)
if let sublayers = self.layer.sublayers as? [CAShapeLayer]
{
for layer in sublayers
{
if layer.path!.contains(point)
{
print("In boundary")
}
}
}
}
但是,当我点击所绘制的形状时,图层将打印到屏幕上,如果我在图层中循环并打印以满足每一层的打印,我将不会得到响应。只是不知道如何正确地捡起我碰过的东西。
这就是我的形状是如何打印的,绿色阴影区域是drawBoundary()的结果,灰色圆圈也是用另一种方法绘制的:
我有一种感觉,就是把这些层作为CALayers,而不是没有.path值的CAShapeLayer。
发布于 2020-04-03 22:30:38
您正在尝试将self.layer.sublayers转换为不太可能发生的CAShapeLayer数组。您需要检查self.layer.sublayers中的每个元素是否是CAShapeLayer。试试这个:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let point = touch!.location(in: self)
guard let sublayers = layer.sublayers else { return }
for sublayer in sublayers {
if let sublayer = sublayer as? CAShapeLayer, let path = sublayer.path {
if path.contains(point) {
print("yes")
}
}
}
}
https://stackoverflow.com/questions/61023673
复制