我正在为我的iPad应用程序构建一个交互式anagram功能,并且我正在尝试使用touchmove事件来使所选项目顺利地跟随运动,但它出现了一些奇怪的原因。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
NSString *touchClass = [NSString stringWithFormat:@"%@",[[touch view] class]];
if ([touchClass isEqualToString:[NSString stringWithFormat:@"%@",[AnagramLetter class]]]) {
NSLog(@"start moving");
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
NSString *touchClass = [NSString stringWithFormat:@"%@",[[touch view] class]];
CGPoint location = [touch locationInView:touch.view];
if ([touchClass isEqualToString:[NSString stringWithFormat:@"%@",[AnagramLetter class]]]) {
NSLog(@"touch view centre (x,y) - (%f,%f)",touch.view.center.x,touch.view.center.y);
NSLog(@"location (x,y) - (%f,%f)",location.x,location.y);
touch.view.center = location;
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
NSString *touchClass = [NSString stringWithFormat:@"%@",[[touch view] class]];
if ([touchClass isEqualToString:[NSString stringWithFormat:@"%@",[AnagramLetter class]]]){
NSLog(@"Now stop moving!");
}
}
以上是我的3种触摸方法,看起来它们应该可以正常工作。您可以在touchesMoved方法中看到我正在检查以查看正在移动的对象是否属于特定类(我为同一个项目创建的自定义类)。有没有人知道为什么会这样?它跟随光标在模拟器中,但它似乎在跟随光标之前捕捉到底角,所以它基本上是在屏幕上跳跃。
有什么想法吗?
答案 0 :(得分:1)
我认为问题在于您正在处理相对于被触摸的子视图的触摸。
[touch locationInView:[touch.view superview]];
会为您提供一个位置,以引用您的自定义视图的父级。
在touchesMoved方法中,您可以查看位移并将相同的位移应用于视图
if ([touchClass isEqualToString:[NSString stringWithFormat:@"%@",[AnagramLetter class]]]) {
UITouch * touch = [touches anyObject];
CGPoint previous = [touch previousLocationInView:[touch.view superview]];
CGPoint current = [touch locationInView:[touch.view superview]];
CGPoint displacement = CGPointMake(current.x - previous.x, current.y - previous.y);
CGPoint center = touch.view.center;
center.x += displacement.x;
center.y += displacement.y;
touch.view.center = center;
}