原理:ide
在按钮上添加拖拽手势UIPanGestureRecognizer,获取手势移动的偏移值,而后从新设置按钮的位置为按钮位置加上偏移值。ui
注意拖拽位置不要超出屏幕位置。最后移除手势是如今在ARC内存管理模式的规范代码风格,相似的有在dealloc里面移除通知、定时器。由于之前在MRC时候是手动建立内存,就必须手动释放内存。如今是在ARC内存管理模式下,不移除也不要紧,只不过是释放迟早的问题。
spa
例子:orm
//仿苹果手机悬浮可拖拽按钮内存
self.cartBtn= [UIButtonbuttonWithType:UIButtonTypeCustom];rem
self.cartBtn.titleLabel.numberOfLines= 0;get
self.cartBtn.titleLabel.font= [UIFontsystemFontOfSize:12];it
[self.cartBtnsetTitle:@" cart\n(可拖拽)"forState:UIControlStateNormal];内存管理
[self.cartBtnsetTitleColor:[UIColorwhiteColor] forState:UIControlStateNormal];io
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];
}