Pages

July 24, 2013

Move UIView to a new location (with offset from origin)

Simple but powerful and useful Objective-C method that moves around a UIView.
I always use it because of no-rewriting of the same code again and again and again.


/** Moves a UIView origin to a new point taking into accout an offset from origin.

 It's especially useful for dragging a View while binding it under a finger.
 Please note that the anchor point is the origin (usually the top-left corner).

 @param obj A UIView or a subclass of UIView.
 @param coord Target point.
 @param offsetFromOrigin Offset X and Y from actual origin.
 @see moveView:toPoint:
 @see resizeView:toSize:

 */
+ (void)moveView:(UIView *)obj toPoint:(CGPoint)coord withOffsetFromOrigin:(CGPoint)offsetFromOrigin {
    if (!obj) { return; }
    CGPoint newCoord = CGPointMake(coord.x + offsetFromOrigin.x, coord.y + offsetFromOrigin.y);
    CGRect r = obj.frame;
    r.origin = newCoord;
    obj.frame = r;
}



Download the ready-for-use source file (.m) of Move UIView to a new location (with offset from origin)

No comments:

Post a Comment