项目要求:
主界面有个悬浮按钮,可以随手指移动而移动,按钮移动停止后按钮回到屏幕边缘。
思路:
自定义一个按钮,在
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event;
方法中实现按钮位置随手指移动而移动
在
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event;
方法中实现一些动画操作
实现:
@implementation SuspensionButton
- (instancetype)init
{
self = [super init];
if (self) {
self.frame = CGRectMake(0, 0, kScale(40), kScale(40));
self.layer.cornerRadius = kScale(20);
self.layer.masksToBounds = YES;
self.backgroundColor = kHexColor(0x98FB98);
self.center = CGPointMake(0, kScreenHeight/2.f);
}
return self;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[super touchesMoved:touches withEvent:event];
UITouch *touch = [touches anyObject];
// 本次的触点和上次触点
CGPoint currentPoint = [touch locationInView:self];
CGPoint previousPonit = [touch previousLocationInView:self];
CGPoint center = self.center;
//中心点移动后的位置
center.x += currentPoint.x - previousPonit.x;
center.y += currentPoint.y - previousPonit.y;
// 限制范围
if (center.x > kScreenWidth - self.frame.size.width/2.f) center.x = kScreenWidth - self.frame.size.width/2.f;
if (center.x < self.frame.size.width/2.f) center.x = self.frame.size.width/2.f;
if (center.y > kScreenHeight - self.frame.size.height/2.f) center.y = kScreenHeight - self.frame.size.height/2.f;
if (center.y < self.frame.size.height/2.f) center.y = self.frame.size.height/2.f;
self.center = center;
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[super touchesEnded:touches withEvent:event];
if (self.center.x < kScreenWidth/2.f) {// 回左边
[self endAnimationWithInterPoint:CGPointMake(self.frame.size.width/2.f, self.center.y) endPoint:CGPointMake(0, self.center.y)];
} else {// 回右边
[self endAnimationWithInterPoint:CGPointMake(kScreenWidth - self.frame.size.width/2.f, self.center.y) endPoint:CGPointMake(kScreenWidth, self.center.y)];
}
}
#pragma mark -- animation
- (void)endAnimationWithInterPoint:(CGPoint)interPoint endPoint:(CGPoint)endPoint{
/*
dampingRatio:0~1,越小弹簧震动越明显
velocity:初始的速度,数值越大一开始移动越快
*/
[UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.75 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.center = interPoint;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.center = endPoint;
} completion:^(BOOL finished) {
}];
}];
}
注:UITouch相关知识点可以看这篇文章https://www.jianshu.com/p/ef60a6c10a8d