【发布时间】:2011-05-21 14:56:46
【问题描述】:
我需要这样做:
以 UIImageViews 作为其子视图的 UISCrollView。当用户点击 UIImageViews 时,就会发生一个动作。但是当用户想要滚动时,即使在 UIImageView (在 UIImageView 的 UIImage 显示的位置)开始滚动,UIScrollView 也应该滚动。
基本上我可以得到以下两种情况之一:
我可以知道,如果用户点击 UIImageView(它是 UIScrollView 的子视图),则会发生一个动作,但是当您尝试通过从 UIImageView 拖动手指来滚动时,该动作也会发生(我希望发生滚动) .
我可以做到这一点,无论用户在哪里点击,视图都会滚动,但如果用户点击 UIImageView,该操作将不会发生。
我无法为您提供我的任何代码,因为我在这里和那里测试了很多 aprroches,它有点混乱,所以它根本没有用(没有大量评论)。
是否有一个干净简单的解决方案可以做到这一点?
好的,这里有一些代码:
-(UIView*) hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
if(isDragging == NO)
{
return [super hitTest:point withEvent:event];
}
NSLog(@"dragging ><><><><><>>><><><><>");
return nil;
}
现在,如果我返回 nil,那么我可以滚动,但我无法点击我的 UIImageView 进行操作。如果我返回 [super hitTest:point withEvent:event] 我无法滚动我的 UIIMageView。
isDragging 是用于确定我是在尝试滚动还是只是点击的测试代码。但是在我可以根据正在发生的事件设置 isDragging 属性之前发生命中测试。
这是我的初始化
-(id) initWithCoder:(NSCoder *)aDecoder
{
if(self = [super initWithCoder:aDecoder])
{
[self setUserInteractionEnabled:YES];
UISwipeGestureRecognizer *swipeRecLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe)];
swipeRecLeft.direction = UISwipeGestureRecognizerDirectionDown;
UISwipeGestureRecognizer *swipeRecRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe)];
swipeRecRight.direction = UISwipeGestureRecognizerDirectionUp;
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSingle)];
[self addGestureRecognizer:swipeRecRight];
[self addGestureRecognizer:swipeRecLeft];
[self addGestureRecognizer:singleTap];
[swipeRecLeft release];
[swipeRecRight release];
[singleTap release];
isDragging = NO;
}
else {
self = nil;
}
return self;
}
这是其余的操作
-(void) tapSingle
{ [self.delegate hitOccur]; }
-(void) swipe
{
isDragging = YES;
}
在我的 UIScrollView 中,我设置了委托,当滚动结束时,我在 UIScrollView 的每个子视图上手动将 isDragging 属性设置为 NO。
它正在工作......但它并不完美。要实际滚动内容,我必须在 UIImageView 中滑动两次(第一个是将 isDragging 设置为 YES,然后我们可以滚动...)。这要怎么做才对?
最新更新:
好的,我已经设法解决了这个问题。但是我很确定我的方式不干净或不好(但不管它是否有效)。
在我的 UIScrollView 子类中,我用这个覆盖了 hitTest 方法:
-(UIView*) hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
if(!self.dragging)
{
if([[super hitTest:point withEvent:event] class] == [ResponsiveBookView class])
{
container = [super hitTest:point withEvent:event];
}
}
return self;
}
容器是 id 容器,它包含我的 UIView 子类。所以我可以识别触摸是在我的图像上还是在滚动视图本身上。现在我需要检测它是滚动还是触摸,我在这里执行此操作:
-(void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event
{
if (!self.dragging) {
NSLog(@"touch touch touch");
[container tapSingle];
[self.nextResponder touchesEnded: touches withEvent:event];
}
[super touchesEnded: touches withEvent: event];
}
如您所见,如果 self.dragging(滚动)将应用默认行为。如果 !self.dragging 我将在我的容器上手动调用 tapSingle (这将使一个动作“发生”)。有效!
【问题讨论】:
标签: iphone ipad uiscrollview scroll