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

猜你喜欢

转载自blog.csdn.net/dopamy_busymonkey/article/details/80788876