2017-02-06 7 views
0

GestureRecognzierをサブビューに追加する方法についていくつかの回答がありましたが、私の問題はサブビューのフレームをあらかじめ用意していないことです。私はCGPathを描画しており、Touches Endedメソッドでは、CGPath境界ボックスに等しいフレームで新しいsubViewを作成したいと思います。その後、subViewPanGestureRecognizerとドラッグしたいと思います。私はEvernote crop機能を実装しようとしていますが、ユーザーが特定の領域を選択して別の位置に移動すると、これはその解決策には正しいアプローチですか?CGPathを使用してサブビューを作成し、そのサブビューにUIPanGestureRecognizerを追加するより

答えて

0

UIGestureRecognizer.frameの関係を理解できません。初期化作業が完了したら、単にオブジェクトにUIGestureRecognizerを追加することができます。 描画サブビューの直後に、TouchEndメソッドにジェスチャを追加してみます。

import UIKit 

class GestureResearchVC: UIViewController{ 

    var subViewByCGPath: UIView? 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 

    func createSubView(){ 
     //creat subview 
     subViewByCGPath = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100)) 
     subViewByCGPath?.backgroundColor = UIColor.yellow 
     let circlePath = UIBezierPath(arcCenter: CGPoint(x: 50,y: 50), radius: CGFloat(20), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true) 

     let shapeLayer = CAShapeLayer() 
     shapeLayer.path = circlePath.cgPath 
     shapeLayer.strokeColor = UIColor.red.cgColor 

     subViewByCGPath?.layer.addSublayer(shapeLayer) 
     self.view.addSubview(subViewByCGPath!) 

     //add pan gesture to subViewByCGPath 
     let gesture = UIPanGestureRecognizer(target: self, action: #selector(panGestureAction(rec:))) 
     subViewByCGPath?.addGestureRecognizer(gesture) 
} 

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
     if subViewByCGPath == nil { 
      print("touch end once") 
      createSubView() 
     }else{ 
      print("touch end repeatedly") 
     } 
    } 

    func panGestureAction(rec: UIPanGestureRecognizer){ 
     print("pannnnnnn~") 
     let transPoint = rec.translation(in: self.view) 
     let x = rec.view!.center.x + transPoint.x 
     let y = rec.view!.center.y + transPoint.y 

     rec.view!.center = CGPoint(x: x, y: y) 
     rec.setTranslation(CGPoint(x: 0, y: 0), in: self.view) 

     //distinguish state 
     switch rec.state { 
      case .began: 
       print("began") 
      case .changed: 
       print("changed") 
      case .ended: 
       print("ended") 
      default: 
       print("???") 
     } 
    } 
} 
+0

どのようにGestureRecognizerのような状態を使用できますか?このコードで開始または.cancelled。パンが終わったら、別のアクションを実行したい。またはすぐにサブビューでパンが終了したかどうかを確認できますか?ありがとう – HussnainWaris

+0

'.state'プロパティを使用して、私のコードを閲覧します(編集済み) –

+0

私はsubViewByCGPathを作成し、それを別のサブビューに追加したいとします(DrawingViewと言う)。翻訳のためにpanGestureAction関数でどのような変更をお勧めしますか? – HussnainWaris

関連する問題