【发布时间】:2021-02-16 09:44:54
【问题描述】:
我正在尝试从另一个 tableviewcell 中按下的按钮更新 tableview。 这是我的带有表格视图的 VC 的代码:
import UIKit
class ResultsVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var teamTable: UITableView!
@IBOutlet weak var wordsTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
wordsForTheRound.removeLast()
print(results)
teamTable.delegate = self
teamTable.dataSource = self
wordsTable.delegate = self
wordsTable.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.teamTable {return results.count}
if tableView == self.wordsTable {return results[0].words.count}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.teamTable {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ResultsTeamsCell") as? ResultsTeamsCell {
cell.updateCell(result: results[indexPath.row])
return cell
}
}
if tableView == self.wordsTable {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ResultsWordsCell") as? ResultsWordsCell {
cell.updateCell(wordIncmoing: results[0].words[indexPath.row], tf: results[0].wordIsCorrect[indexPath.row])
return cell
}
}
return UITableViewCell()
}
@IBAction func reloadTables(_ sender: Any) {
teamTable.reloadData()
wordsTable.reloadData()
}
}
以及我需要 teamTable 在我点击按钮时重新加载的 tableviewcell 的代码 TFBtnPressed
import UIKit
class ResultsWordsCell: UITableViewCell {
@IBOutlet weak var word: UILabel!
@IBOutlet weak var TFBtn: UIButton!
func updateCell(wordIncmoing: String, tf: Bool) {
word.text = wordIncmoing
TFBtn.setTitle("\(tf)", for: .normal)
}
@IBAction func TFBtnPressed(_ sender: Any) {
if TFBtn.title(for: .normal) == "false" {
TFBtn.setTitle("true", for: .normal)
changeWordStatus(word: word.text!)
results[0].score += 1
print(results)
} else {
TFBtn.setTitle("false", for: .normal)
changeWordStatus(word: word.text!)
results[0].score -= 1
print(results)
}
}
func changeWordStatus(word: String) {
for i in 0...results[0].words.count - 1 {
if word == results[0].words[i] {
results[0].wordIsCorrect[i] = !results[0].wordIsCorrect[i]
}
}
}
}
看了很多文章,大概是应该设置一个tableview的delegate,但是不知道怎么做。
【问题讨论】:
-
您需要从您的单元格访问 UITableView,但实际上您之间没有链接。在您的单元格中为此添加一个字段并从 cellForRowAtIndexPath 填充它
-
@jean-baptiste-yunès 我正在使用两个不同的表格视图。我需要从 TableViewCell2 更新 TableView1
-
几乎一样的答案,对象必须相互认识才能通信。
-
@Jean-BaptisteYunès 我是 swift 新手,能否提供更多信息和代码,如何操作?
标签: ios swift uitableview