在 iOS 開(kāi)發(fā)過(guò)程中,經(jīng)常遇到這種需求,構(gòu)建一個(gè)公用的功能以供多個(gè) ViewController 使用。這里我們?cè)跇?gòu)建這個(gè)公用功能模塊的時(shí)候,需要考慮到兩方面。 一:減少代碼重復(fù); 二:避免產(chǎn)生Massive ViewController
? 一個(gè)常見(jiàn)的使用場(chǎng)景就是,構(gòu)建一個(gè)公用的 Loading 加載視圖,和一個(gè)Error Handling 錯(cuò)誤處理模塊。今天的 Blog 就講一講使用如何 Child ViewController 來(lái)構(gòu)建這兩個(gè)公用模塊。
? 思考:我們可以把這些公用模塊的代碼放在那里?
方案一:我們可以在基類完成公用模塊的封裝
class BaseViewController: UIViewController {
func showActivityIndicator() {
...
}
func hideActivityIndicator() {
...
}
func handle(_ error: Error) {
...
}
}
方案一優(yōu)點(diǎn)和缺點(diǎn):
- 優(yōu)點(diǎn): 只要繼承了基類 BaseViewController 的子類就都能使用這個(gè)公用模塊了。
- 缺點(diǎn):如果我們的 ViewController 想要繼承于 UITablewViewController ,豈不是沒(méi)法使用這個(gè)公用模塊了,不太靈活。
- 因?yàn)椴粔蜢`活,我們考慮使用從iOS5之后引入的 Child ViewController 的 Featrue。
方案二:使用 Child ViewController 將我們的公用模塊作為 'Plugin' 鏈接進(jìn)來(lái)
用 Child ViewController 比基類顯示加載視圖的好處在于:任何 ViewController 想要展示一個(gè)加載視圖,只需要把 LoadingViewController 作為 Child 添加進(jìn)來(lái)即可.
- 首先定義一個(gè) ViewController 用來(lái)展示加載視圖,其中這個(gè)VC有自己的生命周期,我們添加一個(gè)菊花即可。
class LoadingViewController: UIViewController {
private lazy var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(activityIndicator)
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// We use a 0.5 second delay to not show an activity indicator
// in case our data loads very quickly.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
self?.activityIndicator.startAnimating()
}
}
}
-
添加和移除 Child VC
- 添加 Child VC:
// Add the view controller as a child addChildViewController(child) // Move the child view controller's view to the parent's view view.addSubview(child.view) // Notify the child that it was moved to a parent child.didMove(toParentViewController: self)- 移除 Child VC:
// Notify the child that it's about to be moved away from its parent child.willMove(toParentViewController: nil) // Remove the child child.removeFromParentViewController() // Remove the child view controller's view from its parent child.view.removeFromSuperview() 每次需要添加 Child VC如果都需要寫(xiě)上面三行代碼就太麻煩了,我們寫(xiě)一個(gè) UIViewController 的 Extension ,封裝兩個(gè)方法add(_ childVC: UIViewController ) remove(),其他任何想要添加或者移除 Child VC,調(diào)用這兩個(gè)封裝的方法即可。
extension UIViewController {
func add(_ child: UIViewController) {
addChildViewController(child)
view.addSubview(child.view)
child.didMove(toParentViewController: self)
}
func remove() {
guard parent != nil else {
return
}
willMove(toParentViewController: nil)
removeFromParentViewController()
view.removeFromSuperview()
}
}
- 上面準(zhǔn)備工作都做好了,開(kāi)始使用 Child VC吧
let loadingVC = LoadingViewController()
self.add(loadingVC)
//開(kāi)始網(wǎng)絡(luò)請(qǐng)求,加載數(shù)據(jù)
dataLoader.loadItems(failedWithError: { [weak self] (error) in
//拿到返回結(jié)果之后remove掉菊花
loadingVC.remove()
//展示錯(cuò)誤視圖
if (error != nil) {
self?.showError()
} else {
//沒(méi)有錯(cuò)誤,提示成功
self?.errorVC.remove()
self?.resultTextView.text = "這是我獲取的正確數(shù)據(jù):請(qǐng)關(guān)注我的簡(jiǎn)書(shū)B(niǎo)log:http://www.itdecent.cn/u/395eedc160ca"
self?.loadDataButton.isHidden = true
}
})
}
- Error View 原理相同,詳細(xì)代碼請(qǐng)見(jiàn)Github鏈接
https://github.com/sishenyihuba/ChildViewControllerDemo

總結(jié)
? 使用 Child ViewController可以使得控制器的代碼規(guī)模降低,降低各個(gè)模塊之間耦合性,把某一個(gè)特定功能的模塊封裝起來(lái),達(dá)到一次Coding,多處多次使用的效果。 在工作中,大家也可以多思考思考什么情況下,可以把某個(gè)模塊封裝成一個(gè)Child ViewController,然后插入到其他 ViewController 中使用