如何找到按下的子层?

How to find what sublayer was pressed?

我有一个 UIImageView,有 2 个子层,代表 2 个不同的图像。 有没有办法确定按下了哪一层?

当前代码

let point = sender.location(in: flagImageView) // Where you pressed

    guard let sublayers = flagImageView.layer.sublayers else { return }
    if let layer = sublayers.first(where: {[=10=].name == "Upper_Image"})?.hitTest(point) {
        print("Found it: \(layer)")
    }

这是添加图片的方法

let distance: CGFloat = 4

    let downMaskPath = UIBezierPath()
    downMaskPath.move(to: CGPoint(x: 0, y: 0))
    downMaskPath.addLine(to: CGPoint(x: self.frame.width - distance, y: 0))
    downMaskPath.addLine(to: CGPoint(x: 0, y: self.frame.height))
    downMaskPath.close()

    let upperMaskPath = UIBezierPath()
    upperMaskPath.move(to: CGPoint(x: self.frame.width, y: 0))
    upperMaskPath.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height))
    upperMaskPath.addLine(to: CGPoint(x: distance, y: self.frame.height))
    upperMaskPath.close()
    upperMaskPath.stroke()

    let imageLayer1 = CALayer()
    imageLayer1.borderColor = #colorLiteral(red: 0.07843137255, green: 0.1294117647, blue: 0.7176470588, alpha: 1).cgColor
    imageLayer1.borderWidth = 1
    imageLayer1.contents = image1?.cgImage // Assign your image
    imageLayer1.frame = self.frame // Define a frame

    let imageLayer2 = CALayer()
    imageLayer2.borderColor = #colorLiteral(red: 0, green: 0.4431372549, blue: 1, alpha: 1).cgColor
    imageLayer2.borderWidth = 1
    imageLayer2.contents = image2?.cgImage // Assign your image
    imageLayer2.frame = self.frame // Define a frame

    let maskLayer1 = CAShapeLayer()
    maskLayer1.path = downMaskPath.cgPath
    imageLayer1.mask = maskLayer1

    let maskLayer2 = CAShapeLayer()
    maskLayer2.path = upperMaskPath.cgPath
    imageLayer2.mask = maskLayer2

    self.layer.addSublayer(imageLayer1)
    self.layer.addSublayer(imageLayer2)

你可以为CALayer使用名称属性,以在各个层之间唯一标识。

像这样:

imageLayer1.name = "someName"

根据苹果

 /* The name of the layer. Used by some layout managers. Defaults to nil. */

    /** Miscellaneous properties. **/
    open var name: String?