美文网首页
学习笔记:UIPanGestureRecognizer

学习笔记:UIPanGestureRecognizer

作者: _sun1993 | 来源:发表于2016-11-02 22:45 被阅读0次

UIPanGestureRecognizer实现左右滑动
1.添加手势和观察者
// 添加pan手势
[self.view addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]];

// 添加观察者监听oneView的frame的改变
[self.oneView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionOld context:nil];

2.监听手势和观察者
// 监听观察者

  • (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
    {
    if (self.oneView.frame.origin.x > 0) {
    self.threeView.hidden = YES;
    }else if (self.oneView.frame.origin.x < 0)
    {
    self.threeView.hidden = NO;
    }
    }

  • (void)dealloc
    {
    NSLog(@"移除");
    [self.oneView removeObserver:self forKeyPath:@"frame"];
    }
    // 监听手势

  • (void)pan:(UIPanGestureRecognizer *)pan
    {
    // 获取手势移动的位置 self.view:规定区域
    CGPoint point = [pan translationInView:self.view];
    // 获取位置水平的偏移量
    CGFloat offsetX = point.x;
    // 改变oneView的frame
    self.oneView.frame = [self frameWithOffsetX:offsetX];

    // 复位 否则pan的偏移量会递增
    [pan setTranslation:CGPointZero inView:self.view];

// 判断拖动结束的时候
if (pan.state == UIGestureRecognizerStateEnded) {
    CGFloat target = 0;
    if (self.oneView.frame.origin.x > [UIScreen mainScreen].bounds.size.width * 0.5) {
        target = self.view.bounds.size.width * 0.2;
    }
    // 获取x偏移量
    CGFloat constant = self.view.bounds.size.width - target;
    // 便宜
    self.oneView.frame = target == 0 ? self.view.bounds : CGRectMake(constant, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    
}

}

相关文章

网友评论

      本文标题:学习笔记:UIPanGestureRecognizer

      本文链接:https://www.haomeiwen.com/subject/xofbuttx.html