我正在開發一個 iOS 應用程式,我想UITableView從不同的控制器重新加載 a 的資訊。為了做到這一點,我的控制器的參考MainViewController與UITableView在稱為另一個控制器(AirlinesController)。
我在重新加載UITableView第一個控制器的資料時遇到問題,它幾乎搞砸了:
主視圖控制器

您可以看到的表格的每個單元格都導致AirlinesController:
航空公司控制器

所以,“應用”按鈕,用戶點擊之后,UITableView的MainViewController多載使用mainView.reloadData()。在這個例子中,我想看到MainViewController標題為“Embraer”的單元格有一個帶有文本“Completed”的綠色標簽,而標題為“Airbus”的單元格有一個標題為“Employee”的黃色標簽,但這是我重新加載表格后得到的結果:

為什么表格的最后一個單元格將其中一個標簽顏色更改為黃色?
這是我正在使用的代碼:
主視圖控制器
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell", for: indexPath) as! CellController
let items = self.gameView.data!.levels
cell.model.text = items[indexPath.row].name
if items[indexPath.row].id < self.gameView.game!.level.id {
cell.cost.text = "Complete"
cell.cost.textColor = UIColor.systemGreen
cell.accessoryType = .none
cell.isUserInteractionEnabled = false
} else if items[indexPath.row].id == self.gameView.game!.level.id {
cell.cost.text = "Employee"
cell.cost.textColor = UIColor.systemYellow
cell.accessoryType = .none
cell.isUserInteractionEnabled = false
} else {
cell.cost.text = "\(items[indexPath.row].XP) XP"
}
return cell
}
航空公司控制器
@IBAction func apply(_ sender: Any) {
if (mainView.game.XP >= level.XP) {
let new_salary = Int(Float(mainView.game.salary) * level.salaryMultiplier)
let new_XP = Int(Float(mainView.game.XPSalary) * level.XPMultiplier)
mainView.game.salary = new_salary
mainView.game.XPSalary = new_XP
mainView.salaryLabel.text = "\(new_salary) $"
mainView.XPLabel.text = "\(new_XP) XP"
mainView.workingFor.text = "Currently working for \(level.name)"
mainView.game.level = Level(id: level.id, name: level.name, XP: 0, XPMultiplier: 1, salaryMultiplier: 1, aircrafts: [Aircraft]())
mainView.saveGame()
DispatchQueue.main.async {
self.mainView.levelItems.reloadData()
self.navigationController?.popViewController(animated: true)
}
} else {
let alert = UIAlertController(title: "Error", message: "Not enough experience to apply!", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: nil))
self.present(alert, animated: true)
}
}
我怎樣才能解決這個問題?
uj5u.com熱心網友回復:
這是因為細胞的重復使用。
在 else 條件下設定默認顏色。
} else {
cell.cost.textColor = UIColor.gray
cell.cost.text = "\(items[indexPath.row].XP) XP"
}
另一種方式,您可以在prepareForReuse方法內部設定默認樣式屬性UITableViewCell
class TableViewCell: UITableViewCell {
override func prepareForReuse() {
super.prepareForReuse()
// Set default cell style
}
}
uj5u.com熱心網友回復:
TableViewCell一直重復使用。我的建議是每次都必須設定默認顏色。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell", for: indexPath) as! CellController
cell.cost.textColor = ...your default text color....
...
return cell
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/407082.html
標籤:
上一篇:用影片顫振打開對話框
