how to move a layer by dragging?

﹥>﹥吖頭↗ 提交于 2019-12-12 03:55:13

问题


How to move a layer by dragging after I added the CATextLayer to UIImageView Layer. As I will add more than one layer to UIImageView. So, How can I know which layer I clicked and move it to another position?

Here is my code for drawing text:

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
}

回答1:


UIGestureRecognizer and hitTest() are the way to go:

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

That's about it. My code is a skeleton where I'm assuming you want the layers inside the imageView. But they can be part of the superview if you want.

Again, be careful with how you set up the layers - you need to access them specifically if you have multiple ones to move around. My code was an attempt to use your function. Maybe you could store the layers in an array (if you don't know how many there will be) or as global variables to either the imageView or the view controller.



来源:https://stackoverflow.com/questions/41831037/how-to-move-a-layer-by-dragging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!