ios view控件手势拖动

@property (weak, nonatomic) IBOutlet UIView *dragView;//可以是UIView的子类
@property (nonatomic, strong) UIPanGestureRecognizer *panGestureRecognizer;//添加在视图上的拖动手势
@property (weak, nonatomic) IBOutlet UIButton *btnUnfold;

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.dragView addGestureRecognizer:self.panGestureRecognizer];
    _dragView.layer.cornerRadius = 15;
    _dragView.layer.masksToBounds = YES;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_btnUnfold.bounds byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(8.0, 8.0)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = _btnUnfold.bounds;
    maskLayer.path = maskPath.CGPath;
    _btnUnfold.layer.mask = maskLayer;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIPanGestureRecognizer *)panGestureRecognizer {
    if (!_panGestureRecognizer) {
        _panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragViewMoved:)];
    }
    return _panGestureRecognizer;
}

- (void)dragViewMoved:(UIPanGestureRecognizer *)panGestureRecognizer {
    
    if (panGestureRecognizer.state == UIGestureRecognizerStateChanged) {
        CGPoint translation = [panGestureRecognizer translationInView:self.dragView];
        CGFloat heightDiff = self.tabBarController.tabBar.frame.origin.y - self.dragView.frame.origin.y;
        NSLog(@"heightDiff:%f",heightDiff);
        NSLog(@"dragViewHight:%f",self.dragView.frame.origin.y);
        NSLog(@"tabBarItemHight:%f",self.tabBarController.tabBar.frame.origin.y); // tabBar 高度

        if (self.dragView.frame.origin.y + translation.y + 30 <= self.tabBarController.tabBar.frame.origin.y && self.dragView.frame.origin.y + translation.y + 330 >= self.tabBarController.tabBar.frame.origin.y) {
            self.dragView.center = CGPointMake(self.dragView.center.x, self.dragView.center.y + translation.y);
            NSLog(@"location X:%f, Y:%f",self.dragView.center.x + translation.x, self.dragView.center.y + translation.y);
        }

        //关键,不设为零会不断递增,视图会突然不见
        [panGestureRecognizer setTranslation:CGPointZero inView:self.view];
    }
}

@end
相关文章
相关标签/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
公众号推荐
   一个健康类的公众号,欢迎关注
小青桔健康