引導(dǎo)頁是App中的基本功能,指導(dǎo)用戶理解某些操作或版本變化等等手形。
引導(dǎo)頁可能出現(xiàn)在任何時候,頁面內(nèi)容會根據(jù)可交互度增加而增加悯恍,而且库糠,引導(dǎo)頁一般為一次性展示,頁面存在過多的引導(dǎo)頁邏輯涮毫,會影響到項(xiàng)目功能的架構(gòu)設(shè)計(jì)瞬欧。
這里分享一種基于swift dynomic replacement的解決方案:
一、方法替換:
extension HomeContainerViewController { ?
????@_dynamicReplacement(for: viewWillAppear(_:)) ?
????func guidance_viewWillAppear(_ animated: Bool) { ? ?
????????viewWillAppear(animated) ? ?
????????if AppStatus.guideForHome.isValid { return }? ??
? ? ? ? // display
????}
}
在本案例中罢防,引導(dǎo)頁觸發(fā)點(diǎn)是viewWillAppear黍判,通過替換方法截取觸發(fā)時機(jī),通過判斷條件篙梢,展示引導(dǎo)頁顷帖。
@_dynamicReplacement是swift 5.0之后提供的方法,使用條件:a、自定義類贬墩;b榴嗅、帶有dynamic標(biāo)識符。不支持對原生類方法的替換陶舞,比如UIView嗽测、UIViewController等;
觸發(fā)時機(jī)一般是某個類的某個方法肿孵,比如按鈕點(diǎn)擊唠粥、手勢觸發(fā)、App或?qū)嵗芷诜椒ǖ龋?/p>
狀態(tài)存儲停做,建議針對引導(dǎo)項(xiàng)作單獨(dú)存儲晤愧,便于版本升級管理(清理),可以使用UserDefault-suitname方式蛉腌,創(chuàng)建本地存儲官份,狀態(tài)值采用懶加載:
lazy var isValid = UserDefaults(suiteName: "guide")?.bool(forKey: "guideForHome") ?? false
二、引導(dǎo)頁展示
present(GuideForHomeViewController(self), animated: true, completion: nil)
modalPresentationStyle = .overFullScreen
modalTransitionStyle = .crossDissolve
view.backgroundColor = .clear
采用present方式烙丛,配合轉(zhuǎn)場特性舅巷,可以非常平滑的展示出引導(dǎo)頁。設(shè)置背景色透明或半透明河咽,可以更方便引導(dǎo)頁與業(yè)務(wù)頁面結(jié)合钠右。
三、內(nèi)容繪制
let timeFrame = timeView.superview?.convert(timeView.frame, to: view)
guideImageView.frame = timeFrame ? ?
guideImageView.image = UIGraphicsImageRenderer(size: timeFrame.size) ? ? ?
????????????????????????????????????????????.image(actions: { (renderer) in timeView.layer.render(in: renderer.cgContext) })
UIGraphicsImageRenderer是目前iOS圖片處理的幾個API中最快的一個忘蟹。將原始view提取成image到 guideImageView中飒房,實(shí)現(xiàn)高亮效果。如果需要流程事件響應(yīng)寒瓦,可以分多個step,分別展示不同步驟的引導(dǎo)坪仇。
四杂腰、事件更新
AppStatus.guideForHome.save(true)
dismiss(animated: true, completion: nil)
在引導(dǎo)結(jié)束后,更新狀態(tài)椅文,退出引導(dǎo)頁喂很。
最終效果圖: