使用QMUI实现用户协议对话框

使用QMUI实现用户协议对话框

懒加载用于初始化 TermServiceDialogController 对象。

懒加载 lazy var 的作用

lazy var dialogController: TermServiceDialogController = {
    let r = TermServiceDialogController()
    r.primaryButton.addTarget(self, action: #selector(primaryClick), for: .touchUpInside)
    return r
}()

1. 延迟初始化 (lazy)

​ • dialogController 是懒加载的,也就是说 只有第一次访问时才会创建 TermServiceDialogController 实例

​ • 这样可以节省内存和性能开销,避免未必要的对象初始化。

2. 自定义初始化过程

​ • 在 lazy 闭包中配置 dialogController 的属性:

r.primaryButton.addTarget(self, action: #selector(primaryClick), for: .touchUpInside)

这里为 primaryButton 按钮绑定了点击事件 primaryClick。

3. 返回配置完成的对象

​ • 返回已经配置好的 TermServiceDialogController 实例,供外部直接使用。

执行顺序

​ 1. 当你第一次访问 dialogController 时:

​ • 执行闭包内容,创建 TermServiceDialogController 对象。

​ • 为 primaryButton 绑定点击事件。

​ • 返回该对象。

​ 2. 之后的访问直接返回已经创建的实例,不再重复执行闭包。

调用示例

dialogController.show()  // 弹出对话框

点击 primaryButton 后触发 primaryClick 事件:

@objc func primaryClick() {
    print("Primary button clicked!")
}

为什么要用 lazy?

​ • 避免不必要的初始化,提升性能。

​ • 当 dialogController 未使用时,不会占用内存

​ • 可以在懒加载闭包中完成复杂的初始化和配置。

这种方式常用于配置复杂 UI 控件或管理弹窗对象。

关于 QMUIModalPresentationViewController 的作用

QMUIModalPresentationViewController 是 QMUI 框架 提供的一种模态弹框组件,它对系统原生的 UIViewController 的模态展示 (present) 进行了封装和增强,提供了更多的动画样式、布局控制以及弹框管理功能。

modalController.contentViewController = self

modalController 来管理整个弹窗布局。

具体视图层级:

QMUIModalPresentationViewController
└── TermServiceDialogController.view
    └── contentContainer (TGLinearLayout)
        ├── titleView (UILabel)
        ├── textView (UITextView)
        ├── primaryButton (QMUIButton)
        └── disagreeButton (QMUIButton)

设置弹窗大小

        //设置弹窗的大小
        view.tg_width.equal(.fill)
        view.tg_height.equal(.wrap)

内容容器

        //内容容器
        contentContainer = TGLinearLayout(.vert)
        contentContainer.tg_width.equal(.fill)
        contentContainer.tg_height.equal(.wrap)
        contentContainer.tg_space = 25
        contentContainer.backgroundColor = .white
        contentContainer.tg_gravity = TGGravity.horz.center
        //设置内容容器的边距
        contentContainer.tg_padding = UIEdgeInsets(top: PADDING_LARGE2, left: PADDING_LARGE2, bottom: PADDING_LARGE2, right: PADDING_LARGE2)
        contentContainer.tg_gravity = TGGravity.horz.center
        view.addSubview(contentContainer)

show函数

  func show() {
      modalController = QMUIModalPresentationViewController()

      //渐变效果
      modalController.animationStyle = .fade

      //点击外部不隐藏
      modalController.isModal = true

      //设置要显示的内容控件
      modalController.contentViewController = self

      modalController.showWith(animated: true) ;

  }

流程顺序

外界调用 dialog.show()

创建 QMUIModalPresentationViewController

配置动画、模态属性、内容控制器

modalController.showWith(animated: true)

将 contentViewController.view(即 dialog.view)添加到弹窗内容

执行淡入动画并展示弹窗

你可能感兴趣的:(app开发,swiftui,ios)