Last active
November 12, 2018 18:22
-
-
Save DonMag/d07ed86b431173897196d1255f16b5c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// basic example of using a DataSource class for a table view | |
// the data source will update itself every 2 seconds | |
// and then use the delegate / protocol pattern to tell | |
// the table view controller to update itsef | |
class SFDataSource: NSObject, UITableViewDataSource { | |
weak var theUpdateDelegate: UpdateDelegate? | |
private let reusableIdentifier:String | |
private var theTimer: Timer! | |
var myData = ["1", "2"] | |
init(identifier reusableID:String, delegate: UpdateDelegate) { | |
self.reusableIdentifier = reusableID | |
self.theUpdateDelegate = delegate | |
super.init() | |
theTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true) | |
} | |
@objc func runTimedCode() { | |
let c = myData.count | |
myData.append("\(c + 1)") | |
theUpdateDelegate?.didUpdate() | |
} | |
func numberOfSections(in tableView: UITableView) -> Int { | |
return 1 | |
} | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return myData.count | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCell(withIdentifier: reusableIdentifier, for: indexPath) | |
cell.textLabel?.text = myData[indexPath.row] | |
return cell | |
} | |
} | |
protocol UpdateDelegate: class { | |
func didUpdate() | |
} | |
class MyTableViewController: UITableViewController, UpdateDelegate { | |
var reuseID = "myReuseID" | |
var theDataSource: SFDataSource! | |
func didUpdate() { | |
DispatchQueue.main.async { | |
self.tableView.reloadData() | |
} | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// register a default table view cell | |
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseID) | |
theDataSource = SFDataSource(identifier: reuseID, delegate: self) | |
tableView.dataSource = theDataSource | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment