原理:
在按鈕上添加拖拽手勢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];
}
