需求 - 5 - 悬浮框 - 1中介绍了一种悬浮框的实现,你会发现,又臭又长,又是定时器,又是啥的。
其实仔细想想,无非就是拉拽 ~ 触摸中的move ~ 一个事件罢了,先来看看这个很好的事件的总结:
http://my.oschina.net/aofe/blog/268749
UIButton是集成自UIRespnder的,我们只要重写它的触摸事件就可以了嘛!
实现:
#import "LBDragFloatFourView.h"
@implementation LBDragFloatFourView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
}
return self;
}
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
// rewrite if needed.
}
#pragma mark - 触摸事件.
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"Touch begins");
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CALayer *layer = self.superview.layer.sublayers[0];
layer.position = [touch locationInView:self.superview];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self moveToEdge]; // 停止拉拽,自动停靠边缘.
}
- (void)moveToEdge
{
if (self.center.x <= self.superview.bounds.size.width * 0.5)
{
[UIView animateWithDuration:0.7 animations:^{
self.center = CGPointMake(self.bounds.size.width * 0.5, self.center.y);
}];
}
else
{
[UIView animateWithDuration:0.7 animations:^{
self.center = CGPointMake(self.superview.bounds.size.width - self.bounds.size.width*0.5, self.center.y);
}];
}
}
@end
使用:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];
self.dragFloatView = [[LBDragFloatFourView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
[self.dragFloatView setImage:[UIImage imageNamed:@"onion.png"] forState:UIControlStateNormal];
[self.dragFloatView setShowsTouchWhenHighlighted:YES]; //去掉灰亮
[self.view addSubview:self.dragFloatView];
}