Skip to content

Instantly share code, notes, and snippets.

@diederikh
Created January 5, 2015 10:00
Show Gist options
  • Save diederikh/a510b99981d5d1c2857f to your computer and use it in GitHub Desktop.
Save diederikh/a510b99981d5d1c2857f to your computer and use it in GitHub Desktop.
dequeueUsingReuseID in Swift
import UIKit
class ExpenseListViewController : UITableViewController, UITableViewDataSource, UITableViewDelegate {
struct TableViewCellIdentifiers {
static let BasicCell = "BasicCell"
}
// MARK: - UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// FIXME: What I don't like about this implementation is that I'm duplicating the "desgin" of the "Basic" cell in the storyboard and here in the else branch. I want to keep the storyboard version as it lets me make a segue. Preferably I'd have the app crash if the storyboard design was not available. I could do that by explicitly unpacking the optional I get back from dequeueReusableCellWithIdentifier but that feels "wrong" -- feedback welcome.
let cellReuseID = TableViewCellIdentifiers.BasicCell
if let cell = tableView.dequeueReusableCellWithIdentifier(cellReuseID) as? UITableViewCell {
return self.configureCell(cell, indexPath: indexPath)
} else {
let newCell = UITableViewCell(style: .Default, reuseIdentifier: cellReuseID);
return self.configureCell(newCell, indexPath: indexPath)
}
}
// MARK: - Private
func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) -> UITableViewCell {
cell.textLabel.text = "Row \(indexPath.row)"
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment