Search code examples
objective-ccocoacore-animationdraggable

Draggable CALayer


Any way of making a CALayer draggable by the user? If so, how?

(In Cocoa - Mac)


Solution

  • Layers can not receive mouse events themselves. You would have to do the event handling in the view or view controller containing the layer.

    If a mouseDragged: event originates on a layer (see -[CALayer hitTest:] and -[CALayer containsPoint:] to test this), adjust the layer's position accordingly. You will probably want to disable implicit animations to have the layer follow the mouse pointer immediately (rather than lagging a little behind because of the animation of the position property):

    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    layer.position = ...;
    [CATransaction commit];