项目在需求在界面上添加一个悬浮按钮,最近闲着没事做,正好在简书上看到一篇文章,我就参考一下,改成iOS系统的assistiveTouch.
效果参考下系统的assistiveTouch.按钮.
参考图片:
下面是代码!
#pragma mark -手势事件改变分享按钮位置
-(void)changePostion:(UIPanGestureRecognizer *)pan{
CGPoint point = [pan translationInView:_shareButton];
CGFloat width = [UIScreen mainScreen].bounds.size.width;
CGFloat height = [UIScreen mainScreen].bounds.size.height;
CGRect originalFrame = _shareButton.frame;
if (originalFrame.origin.x >= 0 && originalFrame.origin.x+originalFrame.size.width <= width) {
originalFrame.origin.x += point.x;
}if (originalFrame.origin.y >= 0 && originalFrame.origin.y+originalFrame.size.height <= height) {
originalFrame.origin.y += point.y;
}
_shareButton.frame = originalFrame;
[pan setTranslation:CGPointZero inView:_shareButton];/**/
if (pan.state == UIGestureRecognizerStateBegan) {
_shareButton.enabled = NO;
}else if (pan.state == UIGestureRecognizerStateChanged){
} else {
CGRect frame = _shareButton.frame;
//是否越界
BOOL isOver = NO;
if (frame.origin.x < 0 ) { // 左边x
frame.origin.x = 0;
isOver = YES;
} else if (frame.origin.x+frame.size.width > width ) { //右边x
frame.origin.x = width - frame.size.width;
isOver = YES;
}
if (frame.origin.y < 64 ) { // 顶部y
frame.origin.y = 0;
isOver = YES;
} else if (frame.origin.y + frame.size.height >= height - 64 ) { //底部y
frame.origin.y = height - frame.size.height;
isOver = YES;
// 设置靠边生效范围 在距离顶部64到底部上来64
}else if ( frame.origin.y > 64 & frame.origin.y < height - 64){
if ( frame.origin.x + originalFrame.size.width / 2 < width/2 ) {
frame.origin.x = 0; //左边靠
}else{
frame.origin.x = width - frame.size.width; //右边靠
}
isOver = YES;
}
if (isOver) {
[UIView animateWithDuration:0.3 animations:^{
_shareButton.frame = frame;
}];
}
_shareButton.enabled = YES;
}
}
#pragma mark -lazy
- (UIButton *)shareButton{
if (_shareButton == nil) {
_shareButton = [UIButton buttonWithType:UIButtonTypeSystem];
_shareButton.showsTouchWhenHighlighted = NO;
_shareButton.backgroundColor = [UIColor redColor];
[_shareButton setBackgroundImage:[UIImage imageNamed:@"shareFriends"] forState:UIControlStateNormal];
_shareButton.frame = CGRectMake(self.view.frame.size.width - 70 - 12/2, self.view.frame.size.height - 114/2 - 70 , 60, 60);
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(changePostion:)];
[_shareButton addGestureRecognizer:pan];
}
return _shareButton;
}