如何通过拖动移动图层?

how to move a layer by dragging?

我把CATextLayer添加到UIImageView Layer后如何通过拖动来移动图层。因为我将向 UIImageView 添加不止一层。那么,如何知道我点击了哪一层并将其移动到另一个位置?

这是我绘制文本的代码:

func addText() -> CATextLayer{
    let rect:CGRect = CGRect(x: 50, y: 600, width: 120, height: 60)
    let myAttributes = [
                        NSFontAttributeName: UIFont(name: "HelveticaNeue-Thin", size:18)!,
                        NSForegroundColorAttributeName: UIColor.black.cgColor
                        ] as [String : Any]
    let myAttributedString = NSAttributedString(string: "TEST STRING", attributes: myAttributes)

    let textLayer = CATextLayer()
    textLayer.frame = rect
    textLayer.string = myAttributedString
    textLayer.position = CGPoint(x:150,y:400)
    textLayer.alignmentMode = kCAAlignmentCenter
    return textLayer
}

UIGestureRecognizerhitTest() 是要走的路:

@IBOutlet weak var imageView: ImageView!
let panGesture = UIPanGestureRecognizer()
var newLayer = CATextLayer()

// this is your code above, be careful, you want each layer "named"!
nextLayer = addText()

imageView.layer.addSubLayer(nextLayer)
imageView.addGestureRecognizer(panGesture)

func moveLayer(_ recognizer:UIPanGestureRecognizer) {
    let p = recognizer.location(in: self)
    if newLayer.hitTest(p) != nil {
        newLayer.position = p
    }
}

就是这样。我的代码是一个骨架,我假设您想要 imageView 中的图层。但如果你愿意,它们可以成为父视图的一部分。

同样,请注意设置图层的方式 - 如果您有多个要移动的图层,则需要专门访问它们。我的代码试图使用您的函数。也许您可以将图层存储在一个数组中(如果您不知道会有多少)或作为 imageView 或视图控制器的全局变量。