iOS开发之实现可拖拽悬浮按钮

原理:

在按钮上添加拖拽手势UIPanGestureRecognizer,获取手势移动的偏移值,然后重新设置按钮的位置为按钮位置加上偏移值。

注意拖拽位置不要超出屏幕位置。最后移除手势是现在在ARC内存管理模式的规范代码风格,类似的有在dealloc里面移除通知、定时器。因为以前在MRC时候是手动创建内存,就必须手动释放内存。现在是在ARC内存管理模式下,不移除也没关系,只不过是释放早晚的问题。

 

例子:

//仿苹果手机悬浮可拖拽按钮

    self.cartBtn= [UIButtonbuttonWithType:UIButtonTypeCustom];

    self.cartBtn.titleLabel.numberOfLines= 0;

    self.cartBtn.titleLabel.font= [UIFontsystemFontOfSize:12];

    [self.cartBtnsetTitle:@"   cart\n(可拖拽)"forState:UIControlStateNormal];

    [self.cartBtnsetTitleColor:[UIColorwhiteColor] forState:UIControlStateNormal];

    self.cartBtn.backgroundColor= [UIColororangeColor];

    [self.viewaddSubview:self.cartBtn];

    [self.cartBtnmas_makeConstraints:^(MASConstraintMaker*make) {

        make.bottom.equalTo(self.mas_bottomLayoutGuide).offset(-40);

        make.right.equalTo(self.view).offset(-30);

        make.width.height.mas_equalTo(@50);

    }];

    //拖拽手势

    self.panGesRecognizer= [[UIPanGestureRecognizeralloc] initWithTarget:selfaction:@selector(onPanGesRecognizer:)];

[self.cartBtnaddGestureRecognizer:self.panGesRecognizer];

 

 

- (void)onPanGesRecognizer:(UIPanGestureRecognizer*)ges {

    

    if(ges.state== UIGestureRecognizerStateChanged|| ges.state== UIGestureRecognizerStateEnded) {

        //translationInView:获取到的是手指移动后,在相对坐标中的偏移量

        CGPointoffset = [ges translationInView:self.view];

        CGPointcenter = CGPointMake(self.cartBtn.center.x+offset.x, self.cartBtn.center.y+offset.y);

        //判断横坐标是否超出屏幕

        if(center.x<= 25) {

            center.x= 25;

        } elseif(center.x>= self.view.bounds.size.width-25) {

            center.x= self.view.bounds.size.width-25;

        }

        //判断纵坐标是否超出屏幕

        if(center.y<= StatusBarHeight+NarBarHeight+25) {

            center.y= StatusBarHeight+NarBarHeight+25;

        } elseif(center.y>= self.view.bounds.size.height-25) {

            center.y= self.view.bounds.size.height-25;

        }

        [self.cartBtnsetCenter:center];

//设置位置

        [ges setTranslation:CGPointMake(0, 0) inView:self.view];

    }

}

 

- (void)removePanGestureRecognizer {

    if(self.panGesRecognizer) {

        [self.cartBtnremoveGestureRecognizer:self.panGesRecognizer];

        self.panGesRecognizer= nil;

    }

}

 

 

- (void)dealloc {

    [selfremovePanGestureRecognizer];

}

posted on 2018-12-19 11:17  HAPPY_CFF  阅读(2069)  评论(0编辑  收藏  举报