iOS---悬浮按钮的创建和使用


因为项目中添加这个功能其实很简单然后研究了一下,记录下供以后回顾

[参考]http://www.myexception.cn/operating-system/1924022.html

悬浮按钮的创建和使用

悬浮按钮

  • 通过UIButton直接创建
  • 通过UIWindow创建按钮
一. 通过UIButton直接创建
原理:用到了UIButton 的UIControlEventTouchDragInside 这个属性,在拖动的时候的时候重新设置UIButton的中心的点的位置

附部分事件:

UIControlEventTouchDragInside
当一次触摸在控件窗口内拖动时。
UIControlEventTouchDragOutside
当一次触摸在控件窗口之外拖动时。
UIControlEventTouchDragEnter
当一次触摸从控件窗口之外拖动到内部时。
UIControlEventTouchDragExit
当一次触摸从控件窗口内部拖动到外部时。
UIControlEventTouchUpInside
所有在控件之内触摸抬起事件。

部分代码:

[self.btn addTarget:self action:@selector(dragMoving:withEvent: )forControlEvents: UIControlEventTouchDragInside];
- (void) dragMoving: (UIButton *) c withEvent:ev
{
    self.a=1;
    c.center = [[[ev allTouches] anyObject] locationInView:self.view];
}
二. 通过UIWindow创建按钮
原理:通过创建一个新的UIWindow,在顶上添加重写之后的UIButton在重写的UIButton里面设置各种的便宜量保证按钮能够依附边界。因为默认的情况下只能存在一个Window我们还需要设置windowLevel。

部分代码:

// 开始触摸,记录触点位置用于判断是拖动还是点击
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
 {
    UITouch *touch = [touches anyObject];
    _startPos = [touch locationInView:_rootView];
}
 手指按住移动过程,通过悬浮按钮的拖动事件来拖动整个悬浮窗口
 */
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 获得触摸在根视图中的坐标
    UITouch *touch = [touches anyObject];
    CGPoint curPoint = [touch locationInView:_rootView];
    // 移动按钮到当前触摸位置
    self.superview.center = curPoint;
}
拖动结束后使悬浮窗口吸附在最近的屏幕边缘

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获得触摸在根视图中的坐标
    UITouch *touch = [touches anyObject];
    CGPoint curPoint = [touch locationInView:_rootView];
switch (minDir) {
        case LEFT:
        {
            [UIView animateWithDuration:0.3 animations:^{
                self.superview.center = CGPointMake(self.superview.frame.size.width/2, self.superview.center.y);
            }];
            break;
        }
        case RIGHT:
        {
            [UIView animateWithDuration:0.3 animations:^{
                self.superview.center = CGPointMake(ScreenW - self.superview.frame.size.width/2, self.superview.center.y);
            }];
            break;
        }
 }

GitDemo

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值