swift 学习记录

在UITableViewCell中使用UIPanGestureR

2019-01-30  本文已影响4人  Tippi

第一步给你的cell添加UIPanGestureRecognizer手势,并设置UIGestureRecognizerDelegate代理

UIPanGestureRecognizer *pan =[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(doPan:)];

pan.delegate = self;

[self addGestureRecognizer:pan];

随后在@implementation中添加下面代码即可

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer

{

    // note: we might be called from an internal UITableViewCell long press gesture

    if([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]){

        UIPanGestureRecognizer *panGestureRecognizer =(UIPanGestureRecognizer*)gestureRecognizer;

        UIView *cell =[panGestureRecognizer view];

        CGPoint translation =[panGestureRecognizer translationInView:[cell superview]];

        // Check for horizontal gesture

        if(fabs(translation.x)> fabs(translation.y))

        {

            return YES;

        }

    }

    return NO;

}

附上swift的代码

override func awakeFromNib(){

    super.awakeFromNib()

    // do not use,say,layoutSubviews as layoutSubviews is called often

    let p = UIPanGestureRecognizer(target: self,action: #selector(yourPan))

    p.delegate = self

    contentView.addGestureRecognizer(p)

    }

}

override func gestureRecognizerShouldBegin(_ g: UIGestureRecognizer)-> Bool {

    if(g.isKind(of: UIPanGestureRecognizer.self)){

        let t =(g as! UIPanGestureRecognizer).translation(in: contentView)

        let verticalness = abs(t.y)

        if(verticalness > 0){

            print("ignore vertical motion in the pan ...")

            print("the event engine will >pass on the gesture< to the scroll view")

            return false

        }

    }

    return true

}

上一篇 下一篇

猜你喜欢

热点阅读