【发布时间】:2013-01-29 04:43:48
【问题描述】:
我需要拖动我的 UIView 对象。我使用这个代码,但它不起作用
float oldX, oldY;
BOOL dragging;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self];
if ([[touch.view class] isSubclassOfClass:[UILabel class]]) {
UILabel *label = (UILabel *)touch.view;
if (CGRectContainsPoint(label.frame, touchLocation)) {
dragging = YES;
oldX = touchLocation.x;
oldY = touchLocation.y;
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
dragging = NO;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self];
if ([[touch.view class] isSubclassOfClass:[UILabel class]]) {
UILabel *label = (UILabel *)touch.view;
if (dragging) {
CGRect frame = label.frame;
frame.origin.x = label.frame.origin.x + touchLocation.x - oldX;
frame.origin.y = label.frame.origin.y + touchLocation.y - oldY;
label.frame = frame;
}
}
}
【问题讨论】:
-
查看这个答案这个 SO 答案stackoverflow.com/a/4983124/1341626
-
实际发生了什么?
-
问题与移动物体有关。当我点击对象时,它必须记住坐标,然后当我们在方法 -touchesMoved 中重新计算它的框架时,它应该移动但它没有。它只向一个方向移动
标签: ios objective-c xcode uiview touchesbegan