injectionIII iOS代碼注入工具(下)
本文將解決如何使用injectionIII對主頁熱重載,如果對injectionIII不瞭解的同學請回到上篇查看
Vaccine
簡單地說Vaccine其實是injectionIII的注入功能無法注入的地方通過它來進行實現,從整體上觀看Vaccine整個框架的文件結構來看,裏面有很多的extension的文件。
Vaccine可以用Cocoapods或者Carthage,也可以手動導入項目中的Source
文件夾。
pod 'Vaccine'
github "zenangst/Vaccine"
Vaccine樣例解析
項目中提供了一個樣例項目,按照下面的步驟配置即可
- Install InjectionIII from the Mac App Store
- git clone [email protected]:zenangst/Vaccine.git
- Run pod install in Example/VaccineDemo/
- Open and run VaccineDemo.xcworkspace
- Select the demo project when InjectionIII wants you to select a folder.
- Start having fun 🤩
(不會有人看不懂吧)
這裏我們在此項目開始解決文章開頭提出的問題:對主頁熱重載。
先展示在AppDelegate中的關鍵代碼:
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Injection.load(then: loadApp).add(observer: self, with: #selector(injected(_:)))
return true
}
private func loadApp() {
//新建HomeVC
//配置self.window
}
private func configureApperance() {
UINavigationBar.appearance().barStyle = .default
UINavigationBar.appearance().tintColor = .blue
}
@objc open func injected(_ notification: Notification) {
/*
TODO: Uncomment line 69 to 70 to change the device resolution you want to test with.
This will also reload the application by invoking `loadApp()` which creates a new main window.
*/
//screenBounds = UIScreen.device(.iPhoneX(orientation: nil))
//loadApp()
/*
TODO: Uncomment line 76 to 92 to show detail controller on each injection.
Animations are temporarely disabled for a better debugging environment.
*/
// guard let flowController = flowController,
// let listController = listViewController else { return }
//
// let contact = Contact(firstName: "John",
// lastName: "Appleseed",
// phoneNumbers: [
// "(888) 555-5512",
// "(888) 555-1212"],
// emails: ["[email protected]"],
// notes: "Some notes"
// )
//
// UIView.setAnimationsEnabled(false)
// flowController.listViewController(listController, didSelect: contact)
// DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
// UIView.setAnimationsEnabled(true)
// }
}
}
樣例中,Vaccine在didFinishLaunchingWithOptions
中實現了InjectionIII的注入和添加響應熱更新的觀察者,另外會調用loadApp方法,也就是我們日常需要實現的homeVC
和self.window
。
每當摁下cmd+s,appdelegate作爲觀察者將會調用injected:
方法,如果想重新刷新homeVC
,你只需要把self.window
和homeVC
重新生成就好了,也就是把loadAPP()
的註釋解開。