需求 - 5 - 悬浮框 - 2

 需求 - 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];
}


就是那么简单,简洁,效果还比之前的好很多,降低了耦合性,还可以在任意UIResponder (UIView)子类轻松使用 ~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值