Javaな日々

NO JAVA, NO LIFE.

ドラッグ&ドロップ可能なImage Viewをコードで作成

上に更にコンポーネントを置いていきたいので,Image Viewをドラッグ可能にしました.ゲームなどで不特定多数の画像をView上に表示させたい時に便利だと思います.
(Quartz CoreフレームワークのLayerを利用する方法では上にコンポーネントを追加するのは難しいですが,処理が速くアニメーションを多用する場合などでは扱いやすいです.)

コード

コードはXcode 4.5にてARC有効状態で作成した場合の例です.
DraggableImageView.h/.m の詳細は参考サイトを参照してください.

DraggableImageView.h
#import <UIKit/UIKit.h>

@interface DraggableImageView : UIImageView {
    CGPoint startLocation;
}

@end
DraggableImageView.m
#import "DraggableImageView.h"

@implementation DraggableImageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    startLocation = [[touches anyObject] locationInView:self];
    [[self superview] bringSubviewToFront:self];
}

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    CGPoint pt = [[touches anyObject] locationInView:self];
    CGRect frame = [self frame];
    
    frame.origin.x += pt.x - startLocation.x;
    frame.origin.y += pt.y - startLocation.y;
    
    [self setFrame:frame];
}

@end
ViewController.m
#import "ViewController.h"
#import "DraggableImageView.h"

@interface ViewController () 

@end

@implementation ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    
    DraggableImageView *img;
    img = [[DraggableImageView alloc] initWithImage:[UIImage imageNamed:@"sample.png"]];
    img.userInteractionEnabled = YES;
    [self.view addSubview:img];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end