使用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 = 25contentContainer.backgroundColor = .whitecontentContainer.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.centerview.addSubview(contentContainer)
show函數
func show() {modalController = QMUIModalPresentationViewController()//漸變效果modalController.animationStyle = .fade//點擊外部不隱藏modalController.isModal = true//設置要顯示的內容控件modalController.contentViewController = selfmodalController.showWith(animated: true) ;}
流程順序
外界調用 dialog.show()
↓
創建 QMUIModalPresentationViewController
↓
配置動畫、模態屬性、內容控制器
↓
modalController.showWith(animated: true)
↓
將 contentViewController.view(即 dialog.view)添加到彈窗內容
↓
執行淡入動畫并展示彈窗