我试图在UIView中检测BezierPaths内部的Taps,并找到了对containsPoint方法的许多引用。但是我似乎找不到从我的ViewController实际引用BezierPaths的方法。
我已经设置:
class func drawSA(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 69, height: 107), resizing: ResizingBehavior = .aspectFit, SACountries: [String: ViewController.CountryStruct])
{
let myPath = UIBezierPath()
myPath.move(to: CGPoint(x: 32.24, y: 8.61))
myPath.addLine(to: CGPoint(x: 31.99, y: 8.29))
myPath.addLine(to: CGPoint(x: 31.78, y: 8.19))
myPath.close()
}
贝塞尔曲线在此函数中绘制,其调用方式为:
override func draw(_ rect: CGRect)
在主ViewController中,我具有以下功能来检测UIView上的Tap:
@objc func SATap(sender: UITapGestureRecognizer)
{
let location = sender.location(in: self.SAView)
// how do I call containsPoint from here?
}
我怎么从这里叫containsPoint?
bezierPaths将在运行时正确绘制。
最佳答案
由于路径是在单独的类中的类函数中创建的,因此无法将其直接保存到视图中。
我通过将UIBezierPaths放入字典中并返回字典来解决了这个问题。数组也可以,但是通过这种方式,我可以轻松访问特定的路径。
class func drawSA(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 71, height: 120), resizing: ResizingBehavior = .aspectFit, SACountries: [String: ViewController.CountryStruct]) -> ([String: UIBezierPath])
{
var Paths = [String: UIBezierPath]()
let myPath = UIBezierPath()
myPath.move(to: CGPoint(x: 32.24, y: 8.61))
myPath.addLine(to: CGPoint(x: 31.99, y: 8.29))
myPath.addLine(to: CGPoint(x: 31.78, y: 8.19))
myPath.close()
Paths["mP"] = myPath
let myPath2 = UIBezierPath()
myPath2.move(to: CGPoint(x: 32.24, y: 8.61))
myPath2.addLine(to: CGPoint(x: 31.99, y: 8.29))
myPath2.addLine(to: CGPoint(x: 31.78, y: 8.19))
myPath2.close()
Paths["mP2"] = myPath2
return Paths
}
然后,我使用
View.addLayer
在视图中创建图层,并在Dictionary上使用For In循环创建它们时,将Layer.name
属性添加到每个图层:for path in Paths.keys.sorted()
{
self.layer.addSublayer(CreateLayer(path)) // The Function simply creates a CAShapeLayer
}
然后,我在手势功能中使用了Dictionary:
@objc func ATap(sender: UITapGestureRecognizer)
{
let location = sender.location(in: self.SAView)
// You need to Scale Location if your CAShapeLayers are Scaled
for path in SAView.Paths
{
let value = path.value
value.contains(location)
if value.contains(location)
{
for (index, layer) in SAView.layer.sublayers!.enumerated()
{
if layer.name == path.key
{
// Do something when specific layer is Tapped
}
}
}
}
}
也许有更好的方法可以做到这一点,但是它一切正常并且运行良好。