Swift 2.0 下面向協議的MVVM架構實踐
自從令人興奮的[《面向協議的編程方法》]在Swift的WWDC大會上發布以來。我對協議的使用考慮了很多。但是在現實中,我并沒有太多的顧及和使用這些功能。我還仍舊在消化到底面向協議的編程方法是什么,在代碼的哪些地方應該使用,而不是使用我目前使用的`go-to`編程方法。
...所以,當我想起來要在哪里應用這些概念性的東西時,我非常激動,那就是MVVM !我已經在之前的博客中使用過MVVM架構,如果你想了解更多MVVM相關知識請參考[這里]。接下來我將講解,如何添加面向協議。
我將會使用一個簡單的例子。一個只有一個設置選項的設置頁面,把應用設置為Minion模式,當然你也可以擴展為多個設置選項。
View Cell
一個極其普通的Cell,它包含一個Label和一個開關控件。你也可以在其他地方使用這個Cell,例如注冊頁面添加一個“記住我”的開關選項。所以,你應該保持這個頁面通用性。
一個復雜的配置
通常,我在cell中使用一個設置方法,來監聽所有對應用設置可能的變更,這看起來是這樣的:
- class SwitchWithTextTableViewCell: UITableViewCell {
- @IBOutlet private weak var label: UILabel!
- @IBOutlet private weak var switchToggle: UISwitch!
- typealias onSwitchToggleHandlerType = (switchOn: Bool) -> Void
- private var onSwitchToggleHandler: onSwitchToggleHandlerType?
- override func awakeFromNib() {
- super.awakeFromNib()
- }
- func configure(withTitle title: String,
- switchOn: Bool,
- onSwitchToggleHandler: onSwitchToggleHandlerType? = nil)
- {
- label.text = title
- switchToggle.on = switchOn
- self.onSwitchToggleHandler = onSwitchToggleHandler
- }
- @IBAction func onSwitchToggle(sender: UISwitch) {
- onSwitchToggleHandler?(switchOn: sender.on)
- }
- }
通過 Swift 的默認參數,可以添加其他的設置選項到這個設置方法,而不必改變代碼中的其他地方,使用起來非常方便。例如,當設計師說開關按鈕的顏色需應該各不相同,這時候我就可以添加一個默認參數。
- func configure(withTitle title: String,
- switchOn: Bool,
- switchColor: UIColor = .purpleColor(),
- onSwitchToggleHandler: onSwitchToggleHandlerType? = nil)
- {
- label.text = title
- switchToggle.on = switchOn
- // color option added!
- switchToggle.onTintColor = switchColor
- self.onSwitchToggleHandler = onSwitchToggleHandler
- }
雖然在這種情況下看起來并不是什么大問題,但是隨著時間的增加,事實上這個方法將會變得非常冗長、復雜!是時候由面向協議的編程方法登場了。
面向協議的編程方法
- protocol SwitchWithTextCellProtocol {
- var title: String { get }
- var switchOn: Bool { get }
- func onSwitchTogleOn(on: Bool)
- }
- class SwitchWithTextTableViewCell: UITableViewCell {
- @IBOutlet private weak var label: UILabel!
- @IBOutlet private weak var switchToggle: UISwitch!
- private var delegate: SwitchWithTextCellProtocol?
- override func awakeFromNib() {
- super.awakeFromNib()
- }
- func configure(withDelegate delegate: SwitchWithTextCellProtocol) {
- self.delegate = delegate
- label.text = delegate.title
- switchToggle.on = delegate.switchOn
- }
- @IBAction func onSwitchToggle(sender: UISwitch) {
- delegate?.onSwitchTogleOn(sender.on)
- }
- }
當設計師說需要改變開關控件顏色的時候會發生什么?以下代碼可以展現協議擴展的奇妙之處。
- extension SwitchWithTextCellProtocol {
- // set the default color here!
- func switchColor() -> UIColor {
- return .purpleColor()
- }
- }
- class SwitchWithTextTableViewCell: UITableViewCell {
- // truncated, see above
- func configure(withDelegate delegate: SwitchWithTextCellProtocol) {
- self.delegate = delegate
- label.text = delegate.title
- switchToggle.on = delegate.switchOn
- // color option added!
- switchToggle.onTintColor = delegate.switchColor()
- }
- }
在以上代碼中協議的擴展實現了默認的switchColor選項,所以,任何已經實現了這個協議或者并不關心設置開關顏色的人,不用關注這個擴展。只有一個具有不同顏色的新的開關控件可以實現。
ViewModel
所以現在剩下的事情將會非常簡單。我將會為MinionMode的設置cell寫一個ViewModel。
- import UIKit
- struct MinionModeViewModel: SwitchWithTextCellProtocol {
- var title = "Minion Mode!!!"
- var switchOn = true
- func onSwitchTogleOn(on: Bool) {
- if on {
- print("The Minions are here to stay!")
- } else {
- print("The Minions went out to play!")
- }
- }
- func switchColor() -> UIColor {
- return .yellowColor()
- }
- }
- ViewController
***一步就是在ViewController中設置cell的時候將ViewModel傳給cell。
- import UIKit
- class SettingsViewController: UITableViewController {
- enum Setting: Int {
- case MinionMode
- // other settings here
- }
- override func viewDidLoad() {
- super.viewDidLoad()
- }
- // MARK: - Table view data source
- override func tableView(tableView: UITableView,
- numberOfRowsInSection section: Int) -> Int
- {
- return 1
- }
- override func tableView(tableView: UITableView,
- cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
- {
- if let setting = Setting(rawValue: indexPath.row) {
- switch setting {
- case .MinionMode:
- let cell = tableView.dequeueReusableCellWithIdentifier("SwitchWithTextTableViewCell", forIndexPath: indexPath) as! SwitchWithTextTableViewCell
- // this is where the magic happens!
- cell.configure(withDelegate: MinionModeViewModel())
- return cell
- }
- }
- return tableView.dequeueReusableCellWithIdentifier("defaultCell", forIndexPath: indexPath)
- }
- }
通過使用協議的擴展,是面向協議的編程方法有了很大的意義,并且我在尋找更多的使用場景。以上代碼的全部內容放在[github]上。
更新:將數據源和代理分開
在評論中,Marc Baldwin 建議分開cell的數據源和代理方法到兩個協議中,就像UITableView中的那樣。我很贊成這個意見,以下是我修改后的代碼。
View Cell
Cell將擁有兩個協議,并且任何一個協議都可以設置這個cell。
- import UIKit
- protocol SwitchWithTextCellDataSource {
- var title: String { get }
- var switchOn: Bool { get }
- }
- protocol SwitchWithTextCellDelegate {
- func onSwitchTogleOn(on: Bool)
- var switchColor: UIColor { get }
- var textColor: UIColor { get }
- var font: UIFont { get }
- }
- extension SwitchWithTextCellDelegate {
- var switchColor: UIColor {
- return .purpleColor()
- }
- var textColor: UIColor {
- return .blackColor()
- }
- var font: UIFont {
- return .systemFontOfSize(17)
- }
- }
- class SwitchWithTextTableViewCell: UITableViewCell {
- @IBOutlet private weak var label: UILabel!
- @IBOutlet private weak var switchToggle: UISwitch!
- private var dataSource: SwitchWithTextCellDataSource?
- private var delegate: SwitchWithTextCellDelegate?
- override func awakeFromNib() {
- super.awakeFromNib()
- }
- func configure(withDataSource dataSource: SwitchWithTextCellDataSource, delegate: SwitchWithTextCellDelegate?) {
- self.dataSource = dataSource
- self.delegate = delegate
- label.text = dataSource.title
- switchToggle.on = dataSource.switchOn
- // color option added!
- switchToggle.onTintColor = delegate?.switchColor
- }
- @IBAction func onSwitchToggle(sender: UISwitch) {
- delegate?.onSwitchTogleOn(sender.on)
- }
- }
ViewModel
你現在可以在擴展里把數據源和delegate邏輯分開了:
- import UIKit
- struct MinionModeViewModel: SwitchWithTextCellDataSource {
- var title = "Minion Mode!!!"
- var switchOn = true
- }
- extension MinionModeViewModel: SwitchWithTextCellDelegate {
- func onSwitchTogleOn(on: Bool) {
- if on {
- print("The Minions are here to stay!")
- } else {
- print("The Minions went out to play!")
- }
- }
- var switchColor: UIColor {
- return .yellowColor()
- }
- }
ViewController
這一部分是我不十分確定,ViewController不能傳遞ViewModel兩次:
- override func tableView(tableView: UITableView,
- cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
- {
- if let setting = Setting(rawValue: indexPath.row) {
- switch setting {
- case .MinionMode:
- let cell = tableView.dequeueReusableCellWithIdentifier("SwitchWithTextTableViewCell", forIndexPath: indexPath) as! SwitchWithTextTableViewCell
- // this is where the magic happens!
- let viewModel = MinionModeViewModel()
- cell.configure(withDataSource: viewModel, delegate: viewModel)
- return cell
- }
- }
- return tableView.dequeueReusableCellWithIdentifier("defaultCell", forIndexPath: indexPath)
- }
代碼已經上傳[GitHub]