ios 空间拖动

1、属性:

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


2、代码:

- (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;
}


- (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.view];
        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];
    }
}

你可能感兴趣的:(iOS,IOS,开发学习)