CocoaPods trunk is moving to be read-only. Read more on the blog, there are 8 months to go.

ZLDraggableFloatingView 0.1.0

ZLDraggableFloatingView 0.1.0

Maintained by fanpeng.



  • By
  • fanpeng

ZLDraggableFloatingView

Version License Platform

ZLDraggableFloatingView 是一个轻量级的 iOS 悬浮按钮组件,基于 UIView 实现,支持拖拽移动、边缘吸附,以及显示和关闭动画。

适合用于以下场景:

  • 全局悬浮入口
  • 快捷操作按钮
  • 客服、反馈、活动入口
  • 调试工具悬浮球

特性

  • 基于 UIView 封装,接入简单
  • 支持用户拖拽移动
  • 支持拖拽结束后自动吸附到左右边缘
  • 可配置边距限制,避免超出父视图可见区域
  • 内置显示与移除动画
  • 拖拽时支持缩放反馈效果

效果说明

组件默认会显示在父视图右下角附近。

拖拽过程中:

  • 视图会跟随手势移动
  • 位置会被限制在父视图范围内
  • 可选地应用轻微缩放反馈

拖拽结束后:

  • 如果 autoAdsorb = YES,会根据当前位置或拖拽速度自动吸附到左侧或右侧边缘
  • 如果 autoAdsorb = NO,则停留在用户释放的位置

安装

CocoaPods

Podfile 中添加:

pod 'ZLDraggableFloatingView'

然后执行:

pod install

环境要求

  • iOS 10.0+
  • Objective-C
  • UIKit

快速开始

#import <ZLDraggableFloatingView/ZLDraggableFloatingView.h>

- (void)setupFloatingView {
    ZLDraggableFloatingView *floatingView = [[ZLDraggableFloatingView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    floatingView.autoAdsorb = YES;
    floatingView.edgeInsets = UIEdgeInsetsMake(20, 20, 34, 20);
    floatingView.dragScaleTransform = CGAffineTransformMakeScale(1.1, 1.1);

    [floatingView showInView:self.view];
}

如果传入 nil

[floatingView showInView:nil];

组件会尝试显示到 keyWindow 上。

API

属性

@property (nonatomic, assign) BOOL autoAdsorb;
@property (nonatomic, assign) UIEdgeInsets edgeInsets;
@property (nonatomic, assign) CGAffineTransform dragScaleTransform;

autoAdsorb

是否在拖拽结束后自动吸附到左右边缘。

  • 默认值:YES

edgeInsets

限制悬浮视图在父视图中的可拖拽范围,同时决定吸附后的边距。

  • 默认值:UIEdgeInsetsMake(10, 10, 10, 10)

dragScaleTransform

拖拽开始时应用的缩放反馈变换。

  • 默认值:CGAffineTransformMakeScale(1.1, 1.1)

方法

- (void)showInView:(nullable UIView *)view;
- (void)dismiss;

showInView:

将悬浮视图添加到指定父视图,并执行入场动画。

  • 传入 view 时:显示在该视图内
  • 传入 nil 时:默认尝试显示在 keyWindow

dismiss

执行缩小淡出动画,并从父视图移除。

默认行为

组件初始化后自带以下默认样式:

  • 绿色背景
  • 圆角为自身宽度的一半,适合做圆形悬浮球
  • 阴影效果

如果你需要自定义内容,可以直接在实例上继续添加子视图,例如:

UILabel *label = [[UILabel alloc] initWithFrame:floatingView.bounds];
label.text = @"Go";
label.textAlignment = NSTextAlignmentCenter;
label.textColor = UIColor.whiteColor;
[floatingView addSubview:label];

示例工程

先进入 Example 目录,再执行:

pod install

然后打开 ZLDraggableFloatingView.xcworkspace 运行示例工程。

适用建议

建议在以下位置创建并持有该视图:

  • 页面级入口:在对应 UIViewController 中管理
  • 全局悬浮入口:在应用主窗口或顶层容器视图中管理

如果你的页面存在底部安全区、TabBar 或自定义工具栏,建议通过 edgeInsets 调整底部间距,避免遮挡。

作者

fanpeng
[email protected]

License

ZLDraggableFloatingView is available under the MIT license. See the LICENSE file for more information.