如何使集合视图响应其自身视图之外的平移手势

时间:2016-09-20 13:39:15

标签: ios swift uicollectionview swift4 uipangesturerecognizer

UICollectionView中有一个UIViewController我想让它回应UICollectionView内外的手势。默认情况下,UICollectionView仅响应其自身view内的手势,但如何让其响应其view之外的滑动?

demo

感谢。

3 个答案:

答案 0 :(得分:4)

我写了一个视图子类,完成了这个:

#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

在界面构建器中,将包含视图的子视图设置为TouchForwardingView,然后将集合视图分配给forwardingTarget属性。

答案 1 :(得分:2)

快速版本的Nailer's anwer,这会将在viewcontroller上完成的所有手势转发到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)
}

答案 2 :(得分:0)

Steven B对Swift 4的回答:)

{{1}}