(順便說一句,非常初學者用戶。我盡力解釋)
我有一個文本框、一個按鈕和一個表格。在應用程式中,您在框中輸入一個數字,然后按下按鈕,表格應填充 10 行,該數字輸入乘以行號。
這是我到目前為止的代碼。
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.
}
}
如何將按鈕鏈接到表格,以便當用戶將數字放入框中然后按下按鈕時表格中的值會發生變化?
uj5u.com熱心網友回復:
假設您實際上UITableView在此視圖控制器中有一個設定作為插座,您需要做的就是呼叫tableView.reloadData()該goButton函式。
然后在cellForRowAt你得到的行號為indexPath.row。將其乘以輸入的數字并將該數字提供給單元配置。
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
}
}
正如您在代碼中看到的,您需要確保您確實有一個表格視圖設定。
該goButton方法只是重新加載表視圖。
計算cellForRowAt行的結果并將其傳遞給單元格配置。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528928.html
標籤:IOS迅速代码
