簡體   English   中英

使用CGPath創建一個子視圖,然后在該子視圖上添加UIPanGestureRecognizer

[英]Create a subView using CGPath and than adding UIPanGestureRecognizer on that subview

我已經看到了有關將GestureRecognzier添加到subViews的幾個答案,但是我的問題是我沒有預先可用的subView框架。 我正在繪制CGPath並在Touches Ended方法中創建了一個等於CGPath邊界框的新子subView 在那之后,我想拖動subViewPanGestureRecognizer 我正在嘗試實現Evernote crop功能,用戶可以在其中選擇特定的視圖區域並將其移動到其他位置。 這是該解決方案的正確方法嗎?

不太了解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("???")
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM