我有一个 UIScrollView ,其中包含一些小的 UIView 子类。UIScrollView 启用了滚动,我希望每个 UIView 都可以在 UIScrollView 内自由拖动。
我的 UIView 子类有这个方法:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([touch view] != self) {
return;
}
CGPoint touchPoint = [touch locationInView:self.superview];
originalX = self.center.x;
originalY = self.center.y;
offsetX = originalX - touchPoint.x;
offsetY = originalY - touchPoint.y;
[self.superview bringSubviewToFront:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([touch view] == self) {
CGPoint location = [touch locationInView:self.superview];
CGFloat x = location.x + offsetX;
CGFloat y = location.y + offsetY;
self.center = CGPointMake(x, y);
return;
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([touch view] == self) {
self.center = CGPointMake(originalX, originalY);
}
}
我发现每次只拖动 UIView 几个像素时都会调用 touchesCancelled:withEvent 。但是如果它是 UIControl 的子类,这些代码将正常工作。为什么?
提前致谢!