(Very beginner user btw. I tried my best to explain)
I've got a text box, a button, and a table. In the app, you put a number in the box, then press the button and the table should populate for, 10 rows, that number input multiplied by the row number.
This is the code I've got so far.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var inputText: UITextField!
@IBAction func goButton(_ sender: Any) {
let input: Int? = Int(inputText.text!)
// should the multiplication happen here or in the tableView func??
// let result: Int? = INDEX OF ROW * input!
//table values should change when button is pressed
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let aCell = tableView.dequeueReusableCell(withIdentifier: "aCell", for: indexPath)
var content = UIListContentConfiguration.cell()
// content = result
aCell.contentConfiguration = content
return aCell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
How do I link the button to the table so that the values in the table will change when a user puts a number into the box and then pressed the button?
CodePudding user response:
Assuming you actually have a UITableView
setup as an outlet in this view controller, all you need to do is call tableView.reloadData()
in the goButton
function.
Then in cellForRowAt
you get the row number as indexPath.row
. Multiply that by the entered number and supply the number to the cell configuration.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var inputText: UITextField!
@IBOutlet weka var tableView: UITableView! // This needs to be added and setup if you don't actually have it
@IBAction func goButton(_ sender: Any) {
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let aCell = tableView.dequeueReusableCell(withIdentifier: "aCell", for: indexPath)
var content = UIListContentConfiguration.cell()
let result = indexPath.row * (Int(inputText.text!) ?? 0)
content.text = "\(result)"
aCell.contentConfiguration = content
return aCell
}
}
As you can see in the code you need to ensure you actually have a table view setup.
The goButton
method simply reloads the table view.
The cellForRowAt
calculates the result for the row and passes it to the cell configuration.