我正在使用CAShapeLayer
在视图中绘制一些形状。我做了一个功能来管理这个。所以,例如:
viewDidLoad()
中的
drawQuad(UIColor(red: 0.600, green: 0.224, blue: 0.341, alpha: 1.00), firstPoint: CGPointMake(screenWidth * -0.159, screenHeight * 0.249), secondPoint: CGPointMake(screenWidth * 0.65, screenHeight * 0.249), thirdPoint: CGPointMake(screenWidth * 1.01, screenHeight * 0.50), fourthPoint: CGPointMake(screenWidth * 0.399, screenHeight * 0.50))
drawQuad(...)
中的
func drawQuad(fillColor: UIColor, firstPoint: CGPoint, secondPoint: CGPoint, thirdPoint: CGPoint, fourthPoint: CGPoint) {
let screenWidth = screenSize.width
let screenHeight = screenSize.height
let shape = CAShapeLayer()
containerLayer.addSublayer(shape)
shape.lineJoin = kCALineJoinMiter
shape.fillColor = fillColor.CGColor
let path = UIBezierPath()
path.moveToPoint(firstPoint)
path.addLineToPoint(secondPoint)
path.addLineToPoint(thirdPoint)
path.addLineToPoint(fourthPoint)
path.closePath()
shape.path = path.CGPath
}
我在尝试为每个形状添加点按识别时遇到困难。我尝试做的是创建一个容器CAShapeLayer
,将每个形状保持为子图层。如果您查看上面的函数,您将在第6行看到这一点。然后,在viewDidLoad()
中,我将最终的容器图层添加到视图中。
这样做的目的是能够像这样hitTest
:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch = touches.first as! UITouch
let location = touch.locationInView(self.view)
for layer in containerLayer.sublayers {
if let hitLayer = layer.hitTest(location) {
println("Tapped")
}
}
}
不幸的是,这似乎不起作用。有谁知道我犯的错误?或者也许我会以错误的方式解决这个问题?
谢谢!