CALayer没有画出概述的地方

时间:2016-12-20 08:36:51

标签: ios swift swift3 calayer catiledlayer

我正在尝试在CATileLayer之上绘制CALayer。基本上,当用户点击图块层时,我想用CALayer更新视图。它没有画出预期的地方:

这里是CATileLayer的课程,它在故事板上有视图

class SquareView: UIView {

    override class var layerClass: AnyClass {
        return CATiledLayer.self
    }

    required init?(coder aDecoder: NSCoder ) {
        super.init(coder: aDecoder)
        guard let layer = self.layer as? CATiledLayer else { return nil }
        layer.contentsScale = 40.0
        layer.tileSize = CGSize(width: 40.0, height: 40.0)
    }

    override func draw(_ rect: CGRect) {

        let context = UIGraphicsGetCurrentContext()
        let red = CGFloat(drand48())
        let green = CGFloat(drand48())
        let blue = CGFloat(drand48())

        context?.setFillColor(red: red, green: green, blue: blue, alpha: 1.0)
        context?.fill(rect)
    }

这是下一个绘制在0.0,0.0的图层,我不知道它为什么不覆盖所需的正方形。

    override func viewDidLoad() {
        super.viewDidLoad()

        let theSelector : Selector = #selector(ViewController.tapGesture)
        let tapGesture = UITapGestureRecognizer(target: self, action: theSelector)
        tapGesture.numberOfTapsRequired = 1
        view.addGestureRecognizer(tapGesture)

    }

    func tapGesture(sender: UITapGestureRecognizer) {
        let theLayer = CALayer()

        let location = sender.location(in: inputView)
        let xInView = location.x
        let yInView = location.y


        let red = CGFloat(drand48())
        let green = CGFloat(drand48())
        let blue = CGFloat(drand48())

        theLayer.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0).cgColor

        theLayer.bounds = CGRect(x: xInView, y: yInView, width: 40.0, height: 40.0)



        view.layer.addSublayer(theLayer)
     }

1 个答案:

答案 0 :(得分:0)

将边界默认值设为0.0,0.0。因此,它最好使用hittest属性,或触摸开始功能来处理这种情况。