我有一個包含 2 個不同單元格的表格視圖。兩個單元都符合相同的協議“WorkoutCellProtocol”,我想避免在出隊期間重寫相同的代碼。未來可能會有更多的細胞,但每個細胞都將遵循相同的協議。
第一個單元格是帶有識別符號的 WorkoutCell:“WorkoutTableViewCell” 第二個單元格是帶有識別符號的 CardioCell:“CardioTableViewCell”
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: WorkoutCellProtocols!
cell.delegate = self
cell.editableRowBorders = colorEditable
cell.numberOfCell = indexPath.row
cell.numberOfExercise = indexPath.section
cell.configureTextFields(model:
exercises[indexPath.row])
if data[indexPath.row].category == "Cardio" {
cell = tableView.dequeueReusableCell(withIdentifier: "CardioTableViewCell", for: indexPath) as! CardioTableViewCell
return cell as! CardioTableViewCell
} else {
cell = tableView.dequeueReusableCell(withIdentifier: "WorkoutTableViewCell") as! WorkoutTableViewCell
return cell as! WorkoutTableViewCell
}
}
當我嘗試以這種方式執行此操作時,因此在頂部只分配一次屬性,在分配型別別之前,我得到“在隱式展開可選值時意外發現 nil”。
uj5u.com熱心網友回復:
首先將您的單元格出列,然后對其進行配置:
var cell: WorkoutCellProtocols
if data[indexPath.row].category == "Cardio" {
cell = tableView.dequeueReusableCell(withIdentifier: "CardioTableViewCell", for: indexPath) as! WorkoutCellProtocols
} else {
cell = tableView.dequeueReusableCell(withIdentifier: "WorkoutTableViewCell") as! WorkoutCellProtocols
}
cell.delegate = self
cell.editableRowBorders = colorEditable
cell.numberOfCell = indexPath.row
cell.numberOfExercise = indexPath.section
cell.configureTextFields(model: exercises[indexPath.row])
return cell
我假設您的協議是這樣宣告的:
protocol WorkoutCellProtocols: UITableViewCell {
...
}
uj5u.com熱心網友回復:
對于任何隱式展開的可選選項,您無法執行您嘗試執行的操作。嘗試將分配向下移動到 if 塊下方,然后將單元格鍵入到協議中,如下所示
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: WorkoutCellProtocols!
if data[indexPath.row].category == "Cardio" {
cell = tableView.dequeueReusableCell(withIdentifier: "CardioTableViewCell", for: indexPath) as! CardioTableViewCell
} else {
cell = tableView.dequeueReusableCell(withIdentifier: "WorkoutTableViewCell") as! WorkoutTableViewCell
}
guard let workoutCell = cell as WorkoutCellProtocols! else { fatalError("Unexpected cell type") }
workoutCell.delegate = self
workoutCell.editableRowBorders = colorEditable
workoutCell.numberOfCell = indexPath.row
workoutCell.numberOfExercise = indexPath.section
workoutCell.configureTextFields(model: exercises[indexPath.row])
return workoutCell
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/408267.html
標籤:
