0
最近我做了一個可以同時拖動多個對象的應用程序。我曾嘗試使用UIPanGestureRecognizer
來獲取手指觸摸的座標,但我無法知道哪個觸摸屬於哪個手指。如何在Xcode中跟蹤多個觸摸
我需要支持四個手指同時平移而不會相互干擾使用Objective-C。
我已經搜索了一段時間的營養,但他們顯示的答案並不適合我。任何幫助,將不勝感激。
最近我做了一個可以同時拖動多個對象的應用程序。我曾嘗試使用UIPanGestureRecognizer
來獲取手指觸摸的座標,但我無法知道哪個觸摸屬於哪個手指。如何在Xcode中跟蹤多個觸摸
我需要支持四個手指同時平移而不會相互干擾使用Objective-C。
我已經搜索了一段時間的營養,但他們顯示的答案並不適合我。任何幫助,將不勝感激。
我在相同的問題上奮鬥了很長時間,終於解決了它。以下是我的DrawView.m
中的代碼,它是UIView
的一個子類,它能夠使用drawRect:
支持圖形。
#import "DrawView.h"
#define MAX_TOUCHES 4
@interface DrawView() {
bool touchInRect[MAX_TOUCHES];
CGRect rects[MAX_TOUCHES];
UITouch *savedTouches[MAX_TOUCHES];
}
@end
@implementation DrawView
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
// Initialization code
self.multipleTouchEnabled = YES;
for (int i=0; i<MAX_TOUCHES; i++) {
rects[i] = CGRectMake(200, 200, 50 ,50);
savedTouches[i] = NULL;
touchInRect[i] = false;
}
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
[[UIColor blueColor] set];
CGContextRef context = UIGraphicsGetCurrentContext();
for (int i=0; i<MAX_TOUCHES; i++) {
CGContextFillRect(context, rects[i]);
CGContextStrokePath(context);
}
}
#pragma mark - Handle Touches
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray *allTouches = [touches allObjects];
for (int i=0; i<[allTouches count]; i++) {
UITouch *touch = allTouches[i];
CGPoint newPoint = [touch locationInView:self];
for (int j=0; j<MAX_TOUCHES; j++) {
if (CGRectContainsPoint(rects[j], newPoint) && !touchInRect[j]) {
touchInRect[j] = true;
savedTouches[j] = touch;
break;
}
}
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray *allTouches = [touches allObjects];
for (int i=0; i<[allTouches count]; i++) {
UITouch *touch = allTouches[i];
CGPoint newPoint = [touch locationInView:self];
for (int j=0; j<MAX_TOUCHES; j++) {
if (touch == savedTouches[j]) {
rects[j] = [self rectWithSize:rects[j].size andCenter:newPoint];
[self setNeedsDisplay];
break;
}
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray *allTouches = [touches allObjects];
for (int i=0; i<[allTouches count]; i++) {
UITouch *touch = allTouches[i];
for (int j=0; j<MAX_TOUCHES; j++) {
if (touch == savedTouches[j]) {
touchInRect[j] = false;
savedTouches[j] = NULL;
break;
}
}
}
}
- (CGRect)rectWithSize:(CGSize)size andCenter:(CGPoint)point {
return CGRectMake(point.x - size.width/2, point.y - size.height/2, size.width, size.height);
}
@end
我將MAX_TOUCHES
設置爲4,因此屏幕上會出現四個對象。其基本概念是當調用touchesBegan::
時,將每個UITouch
ID存儲在savedTouches
數組中,並稍後在調用touchesMoved::
時將每個ID與屏幕上的觸摸進行比較。
只需將代碼粘貼到您的.m
文件中即可使用。抽樣結果如下所示:
希望這有助於:)