移动UIView与触摸有关 [英] Move UIView with relation to touch
本文介绍了移动UIView与触摸有关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图移动与用户触摸相关的UIView。
i'm trying to move a UIView with relation to the user's touches.
这就是我现在所拥有的:
Here's what I have at the moment:
int oldX, oldY;
BOOL dragging;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if (CGRectContainsPoint(window.frame, touchLocation)) {
dragging = YES;
oldX = touchLocation.x;
oldY = touchLocation.y;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if (CGRectContainsPoint(window.frame, touchLocation) && dragging) {
CGRect frame;
frame.origin.x = (window.frame.origin.x + touchLocation.x - oldX);
frame.origin.y = (window.frame.origin.y + touchLocation.y - oldY);
window.frame = frame;
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
dragging = NO;
}
视图从一个位置闪烁到另一个位置,我不知道还有什么可做的。
The view keeps flickering from one location to another, and I don't know what else to do.
任何帮助表示赞赏。
推荐答案
修改 touchesBegan 和 touchesMoved 方法如下所示。
float oldX, oldY;
BOOL dragging;
touchesBegan:withEvent:方法。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if (CGRectContainsPoint(window.frame, touchLocation)) {
dragging = YES;
oldX = touchLocation.x;
oldY = touchLocation.y;
}
}
touchesMoved:withEvent:方法。
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if (dragging) {
CGRect frame = window.frame;
frame.origin.x = window.frame.origin.x + touchLocation.x - oldX;
frame.origin.y = window.frame.origin.y + touchLocation.y - oldY;
window.frame = frame;
}
}
touchesEnded:withEvent:方法。
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
dragging = NO;
}
这篇关于移动UIView与触摸有关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文