ios - 關於拖動手勢簡單應用場景

jialebaba發表於2017-12-19

根據專案需求,需要一個IamgeView達到上下拖動來改變下方View高度的需求,現有手勢中UIPanGestureRecognizer可以實現可以實現起上下左右拖動。

思考:在拖動時是否可以通過判斷x軸和y軸的移動距離來判斷是左右還是上下移動,再來禁止其左右移動。 程式碼部分:

//可拖動ImageView
- (void)setDragImageView{

    self.dragImageView.userInteractionEnabled = YES;
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureClick:)];
    [self.dragImageView addGestureRecognizer:panGesture];

}
- (void)panGestureClick:(UIPanGestureRecognizer *)panGest{
    
    CGPoint panGesturePoint = [panGest translationInView:self.allTitleLowerView];
    
    panGest.view.center = CGPointMake(panGest.view.center.x + 0, panGest.view.center.y - panGesturePoint.y);
    [self.answersViewHeight setConstant: self.answersViewHeight.constant - panGesturePoint.y ];

    if (panGest.state == UIGestureRecognizerStateFailed || panGest.state == UIGestureRecognizerStateEnded) {

        if (panGest.view.center.y < 20) {

            panGest.view.center = CGPointMake(panGest.view.center.x, 21);
            [self.answersViewHeight setConstant: kScreenHeight - 44 - 40];

        }

    }
    //重置拖拽手勢
    [panGest setTranslation:CGPointZero inView:self.view];
}
複製程式碼

最後呈現效果:

ios - 關於拖動手勢簡單應用場景

PS:在網上百度時找到了他人方法需要重新自定義一個手勢繼承 UIPanGestureRecognizer,使用:比較底層的

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
複製程式碼

最終呈現出得效果一樣

相關文章