iOS設備都是可以多點觸摸的,是指手指放在iOS設備的屏幕上從屏幕上拖動或抬起。系統當前視圖響應觸摸事件,若無響應則向上層傳遞,構成響應者鏈。觸摸事件的函數有4個。
創建一個視圖,繼承UIView類,在視圖控制器中把視圖加載到視圖控制器上:
- (void)viewDidLoad
{
[super viewDidLoad];
//創建一個視圖對象,響應觸摸動作
LinView * pView = [[LinView alloc]initWithFrame:CGRectMake(0, 0, 320, 450)];
//設置視圖的背景顏色,與根視圖區別
pView.backgroundColor = [UIColor blueColor];
//把視圖添加到當前視圖,或視圖控制器
[self.view addSubview:pView];
//釋放創建的對象
[pView release];
}在.h文件中添加成員變量:
@interface LinView : UIView
{
//創建一個成員,存放兩點之間距離變化的信息
float _lastDistance;
}
@end在.h文件中對各類事件進行相關的實現、處理:
@implementation LinView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
//??開啟多點觸摸
self.multipleTouchEnabled = YES;
self.userInteractionEnabled = YES;
}
return self;
}
#pragma mark--------觸摸開始時調用此方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//獲取任意一個touch對象
UITouch * pTouch = [touches anyObject];
//獲取對象所在的坐標
CGPoint point = [pTouch locationInView:self];
//以字符的形式輸出觸摸點
NSLog(@"觸摸點的坐標:%@",NSStringFromCGPoint(point));
//獲取觸摸的次數
NSUInteger tapCount = [pTouch tapCount];
//對觸摸次數判斷
if (tapCount == 1)
{
//在0.2秒內只觸摸一次視為單擊
[self performSelector:@selector(singleTouch:) withObject:nil afterDelay:0.2];
}
else if(tapCount == 2)
{
//取消單擊響應,若無此方法則雙擊看做是:單擊事件和雙擊事件
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(singleTouch:) object:nil];
//確定為雙擊事件
[self doubleTouch:nil];
}
}
//單擊方法
- (void)singleTouch:(id)sender
{
//對應單擊時發生的事件
NSLog(@"此時是單擊的操作");
}
//雙擊方法
- (void)doubleTouch:(id)sender
{
//雙擊時對應發生的事件
NSLog(@"此時是雙擊的操作");
}
#pragma mark----------觸摸的移動(滑動)
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//獲取所有的觸摸對象
NSArray * array = [touches allObjects];
//分別取出兩個touch對象
UITouch * pTouch1 = [array objectAtIndex:0];
UITouch * pTouch2 = [array objectAtIndex:1];
//獲取兩個touch對象的坐標點
CGPoint point1 = [pTouch1 locationInView:self];
CGPoint point2 = [pTouch2 locationInView:self];
//用封裝的方法計算兩觸摸點之間的距離
double distance = [self distanceOfPoint:point1 withPoint:point2];
//判斷兩點間距離的變化
if ((distance - _lastDistance) > 0)
{
//兩點距離增大的方法,一般為圖片、文字等的放大,捏合
NSLog(@"兩點距離變大");
}
else
{
//兩點距離減小的方法,一般為圖片、文字等的縮小,放開
NSLog(@"兩點距離變小");
}
//把現在的距離賦值給原來的距離,覆蓋之
_lastDistance = distance;
}
//編寫一個計算兩點之間距離的方法,封裝此方法,方便調用
- (double)distanceOfPoint:(CGPoint)point1 withPoint:(CGPoint)point2
{
double num1 = pow(point1.x - point2.x, 2);
double num2 = pow(point1.y - point2.y, 2);
double distance = sqrt(num1 + num2);
return distance;
}
#pragma mark--------手離開屏幕,觸摸事件結束
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
//觸摸結束時發生的事件
}
#pragma mark--------觸摸事件被打斷,比如電話打進來
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
//一般不寫此方法,可以把程序掛起,放在後台處理
}
@end