Swift CALayer响应点击事件

CALayer类在概念上和UIView类似,同样也是一些被层级关系树管理的矩形块,同样也可以包含一些像图片,文本或者背景的内容。和UIView最大的不同是CALayer不处理用户的交互。但它有一系列的方法帮你处理事件:-containsPoint和-hitTest。

使用containsPoint判断被点击的图层

import UIKit

class ViewController: UIViewController {

var layerView: UIView!
var blueLayer: CALayer!
override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.gray
    self.initBlueLayer()
}

func initBlueLayer()
{
    self.layerView = UIView()
    self.layerView.backgroundColor = UIColor.white
    self.layerView.frame = CGRect(x: 100, y: 200, width: 200, height: 200)
    self.view.addSubview(self.layerView)

    self.blueLayer = CALayer()
    
    self.blueLayer.frame = CGRect(x: 20, y: 20, width: 160, height: 160)
    self.blueLayer.backgroundColor = UIColor.blue.cgColor
    self.layerView.layer.addSublayer(self.blueLayer)     
}    
override func touchesBegan(_ touches: Set, with event: UIEvent?)
{
    
    let touch = touches.first! as UITouch
    var point = touch.location(in: self.view)
    
    point = self.layerView.layer.convert(point, from: self.view.layer)
    
    if self.layerView.layer.contains(point)
    {
        point = self.blueLayer.convert(point, from: self.layerView.layer)
        
        if self.blueLayer.contains(point)
        {
            print("Inside Blue Layer")
        
        }else
        {
            print("Inside White layer")
        
        }
    }
}

点击蓝色区域打印:Inside Blue Layer
点击白色区域打印:Inside White layer

使用hitTest判断被点击的图层

import UIKit

class ViewController: UIViewController {

var layerView: UIView!
var blueLayer: CALayer!
override func viewDidLoad() {
    super.viewDidLoad()
    
    self.view.backgroundColor = UIColor.gray
    self.initBlueLayer()
}

func initBlueLayer()
{
    self.layerView = UIView()
    self.layerView.backgroundColor = UIColor.white
    self.layerView.frame = CGRect(x: 100, y: 200, width: 200, height: 200)
    self.view.addSubview(self.layerView)

    self.blueLayer = CALayer()
    
    self.blueLayer.frame = CGRect(x: 20, y: 20, width: 160, height: 160)
    self.blueLayer.backgroundColor = UIColor.blue.cgColor
    self.layerView.layer.addSublayer(self.blueLayer)
    
}

override func touchesBegan(_ touches: Set, with event: UIEvent?)
{
    
    let touch = touches.first! as UITouch
    let point = touch.location(in: self.view)
    
    let layer = self.layerView.layer.hitTest(point)
    
    if layer == self.blueLayer
    {
         print("Inside Blue Layer")
    
    }else if layer == self.layerView.layer
    {
        print("Inside White layer")
    }else{
    
        print("123")
    
    }
    
}

}

点击蓝色区域打印:Inside Blue Layer
点击白色区域打印:Inside White layer

Swift CALayer响应点击事件_第1张图片
1.png

你可能感兴趣的:(Swift CALayer响应点击事件)