Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
How to automagically generate your Table View rows
class ViewController: UIViewController {
let increment = 5
let maxPercentage = 100
}
extension ViewController: UITableViewDataSource {
// First, we can use this to calculate the number of rows in the Table View.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (maxPercentage/increment)-1 // We subtract 1, since we aren't interested in duplicating the maxPercentage value.
}
// Then we inject data into the rows.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Now we use the percentage in each row to calculate the resulting weight.
let perc = maxPercentage-((1+indexPath.row)*increment)
// The rest is mainly formatting.
let cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
cell.textLabel?.text = "\(perc)%"
cell.textLabel?.textColor = UIColor.gray
let amount = (totalWeight.text! as NSString).doubleValue
cell.detailTextLabel?.text = "\(Double(perc)/100 * Double(amount))"
cell.detailTextLabel?.textColor = UIColor.black
return(cell)
}
@IBAction func weightChanged(_ sender: Any) {
tableView.reloadData()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment