自從使人興奮的[《面向協議的編程方法》]在Swift的WWDC大會上發佈以來。我對協議的使用考慮了不少。可是在現實中,我並無太多的顧及和使用這些功能。我還仍舊在消化到底面向協議的編程方法是什麼,在代碼的哪些地方應該使用,而不是使用我目前使用的`go-to`編程方法。 git
...因此,當我想起來要在哪裏應用這些概念性的東西時,我很是激動,那就是MVVM !我已經在以前的博客中使用過MVVM架構,若是你想了解更多MVVM相關知識請參考[這裏]。接下來我將講解,如何添加面向協議。 github
我將會使用一個簡單的例子。一個只有一個設置選項的設置頁面,把應用設置爲Minion模式,固然你也能夠擴展爲多個設置選項。 編程
View Cell swift
一個極其普通的Cell,它包含一個Label和一個開關控件。你也能夠在其餘地方使用這個Cell,例如註冊頁面添加一個「記住我」的開關選項。因此,你應該保持這個頁面通用性。 架構
一個複雜的配置 app
一般,我在cell中使用一個設置方法,來監聽全部對應用設置可能的變動,這看起來是這樣的: mvvm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
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 的默認參數,能夠添加其餘的設置選項到這個設置方法,而沒必要改變代碼中的其餘地方,使用起來很是方便。例如,當設計師說開關按鈕的顏色需應該各不相同,這時候我就能夠添加一個默認參數。
ide
1
2
3
4
5
6
7
8
9
10
11
12
|
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
}
|
雖然在這種狀況下看起來並非什麼大問題,可是隨着時間的增長,事實上這個方法將會變得很是冗長、複雜!是時候由面向協議的編程方法登場了。
this
面向協議的編程方法
spa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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)
}
}
|
當設計師說須要改變開關控件顏色的時候會發生什麼?如下代碼能夠展示協議擴展的奇妙之處。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
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。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
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邏輯分開了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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兩次:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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]