Permalink
Browse files

Drive table view out of messages store

Rather than storing the messages in a simple array in the view controller, let's separate out responsibilities by creating a MessageStore class. First, let's write the code we wish we had in the view controller. We create a MessageStore, use it to provide the count and message for each table cell. When Save is tapped, we create a new message.

Because we haven't implemented this MessageStore, we get compiler errors. Let's take them one at a time:

Red: Use of undeclared type 'MessageStore'
  • Loading branch information...
CodingItWrong committed Jan 2, 2018
1 parent 860ef42 commit d3112a532cd4c19e7e9b9930c6130ee2b31f7d2b
@@ -44,7 +44,7 @@
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</view>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" id="tew-VC-lKJ">
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="cell" id="tew-VC-lKJ">
<rect key="frame" x="0.0" y="86" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="tew-VC-lKJ" id="iyF-Yw-bqs">
@@ -1,9 +1,37 @@
import UIKit
class MessagesViewController: UITableViewController {
private var store: MessageStore!
@IBOutlet var messageTextField: UITextField!
@IBAction func save() {
guard let text = messageTextField.text else { return }
store.create(text)
messageTextField.text = ""
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
store = MessageStore()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return store.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let message = store.get(indexPath.row)
cell.textLabel?.text = message
return cell
}
}

0 comments on commit d3112a5

Please sign in to comment.