2017-10-30 8 views
0

UIViewでBezierPaths内のタップを検出しようとしていて、containsPointメソッドへの参照が多数見つかりました。しかし、実際にViewControllerからBezierPathsを参照する方法を見つけることができないようです。UIViewでBezierPathを参照する方法

私が設定している

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

をベジエは、次のように呼び出し、この関数の中で描かれています。メインのViewControllerで

override func draw(_ rect: CGRect) 

、私は上のタップを検出するための以下の機能を持っていますUIView:

@objc func SATap(sender: UITapGestureRecognizer) 
{ 
    let location = sender.location(in: self.SAView) 

    // how do I call containsPoint from here? 
} 

ここからcontainsPointをどのように呼び出すことができますか?

実行時にbezierPathsが正しく描画されます。

+0

パスをビューのプロパティとして保存します。 'self.SAView.myPath'でcontainsPathを呼び出します。 – Larme

答えて

0

パスは別のクラス内のクラス関数で作成されるため、ビューに直接保存することはできません。

私はUIBezierPathsを辞書に入れて辞書を返して解決しました。配列も機能しますが、この方法で簡単に特定のパスにアクセスできます。私は、その後に辞書を使用

for path in Paths.keys.sorted() 
    { 
     self.layer.addSublayer(CreateLayer(path)) // The Function simply creates a CAShapeLayer 
    } 

:辞書にループ内での場合でそれらを作成するときに

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を使用し、各レイヤにLayer.nameプロパティを追加しましたジェスチャー機能:

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

これを行うには良い方法があるかもしれませんが、それはすべて機能し、うまく動作します。

関連する問題