Last active
August 20, 2017 18:43
-
-
Save jonyheim/162b0b0dd06367b8d82db965c3bd84a0 to your computer and use it in GitHub Desktop.
How to automagically generate your Table View rows
This file contains 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
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