CALayer not drawing where outlined

246 views Asked by At

I am trying to draw a CALayer on top of a CATileLayer. Basically, when the user taps the tile layer I want to update the view with a CALayer. It's not drawing where expected:

Here's the class for the CATileLayer which has it's over view on the storyboard

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)
    }

Here's the next layer which is drawing at 0.0, 0.0 and I am not sure why it isn't covering the desired square.

    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

There are 1 answers

0
mrabins On

Turns out the bounds defaults to 0.0, 0.0. Therefore, its better to use the hittest property, or touches began function to handle such a case.