原理: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];
}