1、打開(kāi) Xcode,新建一個(gè) Single View Application 項(xiàng)目,給該項(xiàng)目命名為 GesturesAndTouches。
2、在剛剛建立好的項(xiàng)目中,創(chuàng)建三個(gè)文件夾(Option + Command + n),分別命名為 Model、View、Controller。(對(duì)項(xiàng)目文件進(jìn)行合理的歸類)
3、在 View 文件夾中新建一組文件(Command + n),文件的模板選擇 Cocoa Touch Class,把文件命名為 DragView,繼承自 UIImageView 。在這里,我們創(chuàng)建了一個(gè)名為 DragView的視圖類,它是 UIImageView 的子類。
4、在 DragView.m 文件中寫(xiě)入如下代碼:
@implementation DragView
{
CGPoint startLocation;
}
// 初始化方法
- (id)initWithImage:(UIImage *)image {
self = [super initWithImage:image];
if (self) {
// 在初始化成功后,讓該 DragView 實(shí)例對(duì)象具備可交互性(即讓其具備相應(yīng)手勢(shì)的能力)
self.userInteractionEnabled = YES;
}
return self;
}
// Responder 類中的接口方法
// 當(dāng)用戶在屏幕上剛剛開(kāi)始觸摸時(shí),該接口方法被觸發(fā)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 計(jì)算并且存儲(chǔ)偏移量, 把相應(yīng)觸控的視圖置頂
startLocation = [[touches anyObject] locationInView:self];
[self.superview bringSubviewToFront:self];
}
// Responder 類中的接口方法
// 當(dāng)用戶在屏幕上的觸摸處于移動(dòng)狀態(tài),該接口方法被觸發(fā)
// 該方法實(shí)際上在一次觸摸移動(dòng)過(guò)程中會(huì)被調(diào)用很多次
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
// 計(jì)算偏移量
CGPoint point = [[touches anyObject] locationInView:self];
float dx = point.x - startLocation.x;
float dy = point.y - startLocation.y;
// 計(jì)算視圖新的中心點(diǎn)坐標(biāo)
CGPoint newCenter = CGPointMake(self.center.x + dx, self.center.y + dy);
// 確定視圖新的位置
self.center = newCenter;
}
5、導(dǎo)入一張圖片到項(xiàng)目,button.png (注意勾選正確的文件選項(xiàng),Copy items if needed、Create groups,確保是把這場(chǎng)圖片復(fù)制了一份到我們的項(xiàng)目,而不是一個(gè)索引。如果復(fù)制過(guò)來(lái)的是一個(gè)索引,當(dāng)我們的項(xiàng)目文件在其他Mac上打開(kāi)時(shí),是找不到這個(gè)圖片文件的,會(huì)提示文件缺失。其他文件的增添與此同理)。
button.png
6、接下來(lái),我們開(kāi)始使用剛才創(chuàng)建的 DragView。在 ViewController.m 文件中寫(xiě)入如下代碼:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 創(chuàng)建一個(gè) DragView 實(shí)例對(duì)象,并以 button.png 這張圖片來(lái)初始化
DragView *dragView = [[DragView alloc] initWithImage:[UIImage imageNamed:@"button"]];
// 添加到控制器的視圖上
[self.view addSubview:dragView];
}

移動(dòng)前

移動(dòng)后