Swift 2.0 下面向協(xié)議的MVVM架構(gòu)實(shí)踐
自從令人興奮的[《面向協(xié)議的編程方法》]在Swift的WWDC大會上發(fā)布以來。我對協(xié)議的使用考慮了很多。但是在現(xiàn)實(shí)中,我并沒有太多的顧及和使用這些功能。我還仍舊在消化到底面向協(xié)議的編程方法是什么,在代碼的哪些地方應(yīng)該使用,而不是使用我目前使用的`go-to`編程方法。
...所以,當(dāng)我想起來要在哪里應(yīng)用這些概念性的東西時(shí),我非常激動(dòng),那就是MVVM !我已經(jīng)在之前的博客中使用過MVVM架構(gòu),如果你想了解更多MVVM相關(guān)知識請參考[這里]。接下來我將講解,如何添加面向協(xié)議。
我將會使用一個(gè)簡單的例子。一個(gè)只有一個(gè)設(shè)置選項(xiàng)的設(shè)置頁面,把應(yīng)用設(shè)置為Minion模式,當(dāng)然你也可以擴(kuò)展為多個(gè)設(shè)置選項(xiàng)。
View Cell
一個(gè)極其普通的Cell,它包含一個(gè)Label和一個(gè)開關(guān)控件。你也可以在其他地方使用這個(gè)Cell,例如注冊頁面添加一個(gè)“記住我”的開關(guān)選項(xiàng)。所以,你應(yīng)該保持這個(gè)頁面通用性。
一個(gè)復(fù)雜的配置
通常,我在cell中使用一個(gè)設(shè)置方法,來監(jiān)聽所有對應(yīng)用設(shè)置可能的變更,這看起來是這樣的:
- 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 的默認(rèn)參數(shù),可以添加其他的設(shè)置選項(xiàng)到這個(gè)設(shè)置方法,而不必改變代碼中的其他地方,使用起來非常方便。例如,當(dāng)設(shè)計(jì)師說開關(guān)按鈕的顏色需應(yīng)該各不相同,這時(shí)候我就可以添加一個(gè)默認(rèn)參數(shù)。
- 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
- }
雖然在這種情況下看起來并不是什么大問題,但是隨著時(shí)間的增加,事實(shí)上這個(gè)方法將會變得非常冗長、復(fù)雜!是時(shí)候由面向協(xié)議的編程方法登場了。
面向協(xié)議的編程方法
- 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)
- }
- }
當(dāng)設(shè)計(jì)師說需要改變開關(guān)控件顏色的時(shí)候會發(fā)生什么?以下代碼可以展現(xiàn)協(xié)議擴(kuò)展的奇妙之處。
- 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()
- }
- }
在以上代碼中協(xié)議的擴(kuò)展實(shí)現(xiàn)了默認(rèn)的switchColor選項(xiàng),所以,任何已經(jīng)實(shí)現(xiàn)了這個(gè)協(xié)議或者并不關(guān)心設(shè)置開關(guān)顏色的人,不用關(guān)注這個(gè)擴(kuò)展。只有一個(gè)具有不同顏色的新的開關(guān)控件可以實(shí)現(xiàn)。
ViewModel
所以現(xiàn)在剩下的事情將會非常簡單。我將會為MinionMode的設(shè)置cell寫一個(gè)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中設(shè)置cell的時(shí)候?qū)iewModel傳給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)
- }
- }
通過使用協(xié)議的擴(kuò)展,是面向協(xié)議的編程方法有了很大的意義,并且我在尋找更多的使用場景。以上代碼的全部內(nèi)容放在[github]上。
更新:將數(shù)據(jù)源和代理分開
在評論中,Marc Baldwin 建議分開cell的數(shù)據(jù)源和代理方法到兩個(gè)協(xié)議中,就像UITableView中的那樣。我很贊成這個(gè)意見,以下是我修改后的代碼。
View Cell
Cell將擁有兩個(gè)協(xié)議,并且任何一個(gè)協(xié)議都可以設(shè)置這個(gè)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
你現(xiàn)在可以在擴(kuò)展里把數(shù)據(jù)源和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)
- }
代碼已經(jīng)上傳[GitHub]