如何让集合视图对自己视图外的平移手势做出响应

问题描述:

我在UIViewController中有UICollectionView,我希望它响应UICollectionView之外的AND内部的手势。默认情况下,UICollectionView只对其自己的view内的手势做出响应,但是如何才能使其响应在view之外滑动?如何让集合视图对自己视图外的平移手势做出响应

demo

谢谢。

+1

使用'触动:began'在你的'viewController'中 – Santosh

我写的只是实现这个视图子类:

#import <UIKit/UIKit.h> 

@interface TouchForwardingView : UIView 

@property (nonatomic, weak) IBOutlet UIResponder *forwardingTarget; 

- (instancetype)initWithForwardingTarget:(UIResponder *)forwardingTarget; 


@end 

#import "TouchForwardingView.h" 

@implementation TouchForwardingView 

- (instancetype)initWithForwardingTarget:(UIResponder *)forwardingTarget 
{ 
    self = [super init]; 
    if (self) 
    { 
     self.forwardingTarget = forwardingTarget; 
    } 

    return self; 
} 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [super touchesBegan:touches withEvent:event]; 
    [self.forwardingTarget touchesBegan:touches withEvent:event]; 
} 

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [super touchesEnded:touches withEvent:event]; 
    [self.forwardingTarget touchesEnded:touches withEvent:event]; 
} 

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [super touchesCancelled:touches withEvent:event]; 
    [self.forwardingTarget touchesCancelled:touches withEvent:event]; 
} 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [super touchesMoved:touches withEvent:event]; 
    [self.forwardingTarget touchesMoved:touches withEvent:event]; 
} 

@end 

在Interface Builder中,设置包含视图TouchForwardingView的子视图,然后指定集合视图到forwardingTarget财产。

钉枪的前面回答的斯威夫特版本,这将在视图 - 控制做了所有的手势转发到的CollectionView

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    collectionView.touchesBegan(touches, withEvent: event) 
} 
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    collectionView.touchesEnded(touches, withEvent: event) 
} 
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { 
    collectionView.touchesCancelled(touches, withEvent: event) 
} 
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    collectionView.touchesMoved(touches, withEvent: event) 
} 

史蒂芬B的答案与雨燕4 :)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    collectionView.touchesBegan(touches, with: event) 
} 
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    collectionView.touchesEnded(touches, with: event) 
} 
override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) { 
    collectionView.touchesCancelled(touches!, with: event) 
} 
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 
    collectionView.touchesMoved(touches, with: event) 
}