在Swift中检测CAShapeLayer上的点击? [英] Detecting a tap on a CAShapeLayer in Swift?

查看:166
本文介绍了在Swift中检测CAShapeLayer上的点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对iOS开发很新(所以请原谅我的无能 - 我到处寻找!),并且正在寻找一种方法来检测点击 CAShapeLayer 。到目前为止,我遇到了 hitTest 。是 hitTest 最好的方法,如果是这样的话,如何在Swift中使用它,尤其是 CAShapeLayer s?另外,如果我有很多CAShapeLayers,我如何使用hitTest方法单独引用它们?

I'm quite new to iOS Development (so please forgive my ineptitude - I've looked everywhere!), and was looking to find a way to detect a tap on a CAShapeLayer. So far, I've come across hitTest. Is hitTest the best method, and if so how is it used in Swift especially with CAShapeLayers? Also, if I had numerous CAShapeLayers, how would I use the hitTest method to refer to them individually?

这就是我创建CAShapeLayer的方式:

This is how I created the CAShapeLayer:

    let newBounds = CGRect(x: 0, y: 0, width: 200, height: 200)
    let newShape = CAShapeLayer()
    newShape.bounds = newBounds
    newShape.position = view.center
    newShape.cornerRadius = newBounds.width / 2
    newShape.path = UIBezierPath(ovalInRect: newShape.bounds).CGPath

    newShape.lineWidth = 42
    newShape.strokeColor = UIColor(red: 222/255.0, green: 171/255.0, blue: 66/255.0, alpha: 1.0).CGColor
    newShape.fillColor = UIColor.clearColor().CGColor

    newShape.strokeStart = 0.2
    newShape.strokeEnd = 0.4

    view.layer.addSublayer(newShape)


推荐答案

继承人,这是做你想做的最好的方式达成:

Heres imo the best way to do what you want to achieve:

// First add the shapelayer
let layer = CAShapeLayer()
layer.anchorPoint = CGPointZero
layer.path = UIBezierPath(ovalInRect: CGRect(x: 0, y: 0, width: 100, height: 200)).CGPath
layer.bounds = CGPathGetBoundingBox(layer.path) // IMPORTANT, without this hitTest wont work
layer.fillColor = UIColor.redColor().CGColor
self.view.layer.addSublayer(layer)


// Check for touches
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let point = touches.anyObject()!.locationInView(self.view) // Where you pressed

    if let layer = self.view.layer.hitTest(point) as? CAShapeLayer { // If you hit a layer and if its a Shapelayer
        if CGPathContainsPoint(layer.path, nil, point, false) { // Optional, if you are inside its content path
            println("Hit shapeLayer") // Do something
        }
    }
}

这篇关于在Swift中检测CAShapeLayer上的点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆