如何通过拖动移动图层?

时间:2017-01-24 14:43:30

标签: ios swift uiimageview uigesturerecognizer calayer

在将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
}

1 个答案:

答案 0 :(得分:1)

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或视图控制器中。

相关问题