1. 開啓一個專案
2. 加入六張圖片分別當作ICON
3. 加入一個新的Class檔,作為控制圖片移動之用,此處選用UIButton
4.先針對class 的movPicture.h作修改
#import <UIKit/UIKit.h>
@interface movPicture : UIButton
{
CGPoint beginPoint;
}
@property (nonatomic) BOOL dragEnable;
@end
5. 然後在movPicture.m加入觸控的程式碼
#import "movPicture.h"
@implementation movPicture
@synthesize dragEnable;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if (!dragEnable) {
return;
}
UITouch *touch = [touches anyObject];
beginPoint = [touch locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (!dragEnable) {
return;
}
UITouch *touch = [touches anyObject];
CGPoint nowPoint = [touch locationInView:self];
float offsetX = nowPoint.x - beginPoint.x;
float offsetY = nowPoint.y - beginPoint.y;
self.center = CGPointMake(self.center.x + offsetX, self.center.y + offsetY);
}
@end
5. 然後在mainViewController.m加上設定的程式碼
#import "mainViewController.h"
#import "movPicture.h"
@interface mainViewController ()
@end
@implementation mainViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
for (int i=0;i<6;i++)
{
movPicture *tt = [[movPicture alloc] initWithFrame:CGRectMake(i%3*120, (i/3)*120 , 100, 100)];
[tt setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png",i+1]] forState:UIControlStateNormal];
tt.dragEnable = YES;
tt.tag = i;
[self.view addSubview:tt];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
6. 完成後的執行結果,每一個小圖都可以隨意用手指移動




