如何找到被按下的子层?

时间:2018-10-11 07:54:31

标签: ios swift calayer

我有一个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: {$0.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)

1 个答案:

答案 0 :(得分:1)

您可以对CALayer使用name属性,以在各个层之间唯一地标识。

就像这样:

imageLayer1.name = "someName"

根据苹果公司

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

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