在iOS应用中,我有两个跟随用户触摸的UI元素。问题是如果触摸移动到快速,UI元素将停止跟随。 (它还确保UI元素不能移动到某些边界之外)
这是我用来移动UI元素的代码,在移动的触摸上运行:
// Move the pinch UI around
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLoc = [touch locationInView:self.view];
CGPoint imageHeight = CGPointMake((_pinchUI_top.frame.origin.x)+(_pinchUI_top.frame.size.width/2), size_OriginalImage.height);
// Top line
if (CGRectContainsPoint([_pinchUI_top frame], [touch locationInView:self.view])) {
CGPoint touchLocY = CGPointMake((_pinchUI_top.frame.origin.x)+(_pinchUI_top.frame.size.width/2), touchLoc.y);
_pinchUI_top.center = touchLocY;
// If outside of image, stop
if (touchLocY.y > imageHeight.y) {
_pinchUI_top.center = imageHeight;
}
else {
pixelsFromBottom = touchLoc.y;
}
// Bottom line
} else if (CGRectContainsPoint([_pinchUI_bottom frame], [touch locationInView:self.view])) {
CGPoint touchLocY = CGPointMake((_pinchUI_bottom.frame.origin.x)+(_pinchUI_bottom.frame.size.width/2), touchLoc.y);
_pinchUI_bottom.center = touchLocY;
// If outside of image, stop
if (touchLocY.y > imageHeight.y) {
_pinchUI_bottom.center = imageHeight;
}
else {
pixelsFromTop = touchLoc.y;
}
}
}
_pinchUI_top
和_pinchUI_bottom
是两个UI元素。
答案 0 :(得分:0)
使用touchesBegan事件获取原始位置(并处理顶部或底部),因此不要在touchesMoved中进行检查,而是在触摸事件开始时执行此操作。然后在touchesMoved事件中,您可以移动相应的图像。
float topY;
float bottomY;
bool touchValid;
bool touchTop;
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLoc = [touch locationInView:self.view];
float touchY = touchLoc.y;
touchValid = NO;
if (CGRectContainsPoint([_pinchUI_top frame], [touch locationInView:self.view])) {
topY = touchY;
touchTop = YES;
touchValid = YES;
} else if (CGRectContainsPoint([_pinchUI_bottom frame], [touch locationInView:self.view])){
bottomY = touchY;
touchTop = NO;
touchValid = YES;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLoc = [touch locationInView:self.view];
CGPoint imageHeight = CGPointMake((_pinchUI_top.frame.origin.x)+(_pinchUI_top.frame.size.width/2), size_OriginalImage.height);
if (touchValid) {
// Top line
if (touchTop) {
CGPoint touchLocY = CGPointMake((_pinchUI_top.frame.origin.x)+(_pinchUI_top.frame.size.width/2), touchLoc.y);
_pinchUI_top.center = touchLocY;
// If outside of image, stop
if (touchLocY.y > imageHeight.y) {
_pinchUI_top.center = imageHeight;
}
else {
pixelsFromBottom = touchLoc.y;
}
// Bottom line
} else if (!touchTop) {
CGPoint touchLocY = CGPointMake((_pinchUI_bottom.frame.origin.x)+(_pinchUI_bottom.frame.size.width/2), touchLoc.y);
_pinchUI_bottom.center = touchLocY;
// If outside of image, stop
if (touchLocY.y > imageHeight.y) {
_pinchUI_bottom.center = imageHeight;
}
else {
pixelsFromTop = touchLoc.y;
}
}
}
}
这应该解决它。