问题
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