ios - 如何将 UIPanGestureRecognizer 添加到在 CAShapLayer 上绘制的形状 - swift?

标签 ios swift uipangesturerecognizer

我有一个 imageView,我在其层中绘制了一个蓝色圆圈。我希望用户能够在 UIImageView 中的任何位置点击、按住并拖动这个蓝色圆圈。我不确定如何将此形状附加到 UIPanGestureRecognizer。到目前为止,我的努力如下:

class DrawCircleViewController: UIViewController {

    @IBOutlet weak var imgView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // DRAW A FILLED IN BLUE CIRCLE
        drawBlueCircle()

        // ADD GESTURE RECOGNIZER
        let panRecgonizer = UIPanGestureRecognizer.init(target: ???, action: <#T##Selector?#>)

    }

    func drawBlueCircle(){
        let fourDotLayer = CAShapeLayer()
        fourDotLayer.path = UIBezierPath.init(roundedRect: CGRect.init(x: 60, y: 60, width: 30, height: 30), cornerRadius: 50).cgPath
        fourDotLayer.fillColor = UIColor.blue.cgColor
        self.imgView.layer.addSublayer(fourDotLayer)
    }
}

最佳答案

使用此代码移动 View

@objc func handlePanRecgonizer(_ gestureRecognizer: UIPanGestureRecognizer){
     if panRecgonizer.state == .began || panRecgonizer.state == .changed {
        let translation = panRecgonizer.translation(in: self.view)
        panRecgonizer.view!.center = CGPoint(x: panRecgonizer.view!.center.x + translation.x, y: panRecgonizer.view!.center.y + translation.y)
        panRecgonizer.setTranslation(CGPoint.zero, in: self.view)
    }
}

如果您想以编程方式添加UIPanGestureRecognizer:

let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanRecgonizer))
 self.someDraggableView.addGestureRecognizer(gestureRecognizer)

关于ios - 如何将 UIPanGestureRecognizer 添加到在 CAShapLayer 上绘制的形状 - swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52329834/

相关文章:

ios - 如何以编程方式快速发送手势

ios - 如何在不重置位置的情况下更改UIButton?

ios - 更改以相同手势将一个 View 拖动到另一个 View

ios - 在 Swift 中动画循环进度 View

iOS:滑动表格 View 单元格时是否可以覆盖 show-red-delete-button-method?

json - 由于使用 Google Maps API 未捕获异常 'NSRangeException' 而终止应用程序

swift - 为 SKCropNode 分配多个掩码

ios - TabBar 的背景颜色在选项卡选择时发生变化

ios - shouldShowMenuForRowAt 未被调用

ios - 如何为 CoreData 中的特定索引设置值。 iOS swift