Skip to content

Instantly share code, notes, and snippets.

@thefotes
Created July 9, 2013 11:56
Show Gist options
  • Save thefotes/5956796 to your computer and use it in GitHub Desktop.
Save thefotes/5956796 to your computer and use it in GitHub Desktop.
Put an image on the screen and then allow for a user to drag by way of a touch event. This example comes from the book "iOS Programming: The Big Nerd Ranch Guide, Third Edition" by Joe Conway and Aaron Hillegas.
#import "PMViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface PMViewController ()
{
CALayer *boxLayer;
}
@end
@implementation PMViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
boxLayer = [[CALayer alloc] init];
boxLayer.bounds = CGRectMake(0.0,0.0,85.0,85.0);
boxLayer.position = CGPointMake(160.0, 100.0);
UIImage *layerImage = [UIImage imageNamed:@"Hypno.png"];
CGImageRef image = [layerImage CGImage];
boxLayer.contents = (__bridge id)image;
boxLayer.contentsRect = CGRectMake(-0.1, -0.1, 1.2, 1.2);
boxLayer.contentsGravity = kCAGravityResizeAspect;
[self.view.layer addSublayer:boxLayer];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self.view];
boxLayer.position = p;
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self.view];
[CATransaction begin];
[CATransaction setDisableActions:YES];
boxLayer.position = p;
[CATransaction commit];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment