我有三種不同類型的自定義UITableCells。我有一個if語句來設置它們:如何使用if語句將變量的類型設置爲特定類型的自定義tableCell?
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if somePosts[indexPath.row].typeOfPost == .linkPost {
let cell: LinkTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "linkTableViewCell") as! LinkTableViewCell
} else if somePosts[indexPath.row].typeOfPost == .picturePost {
let cell: PictureTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "pictureTableViewCell") as! PictureTableViewCell
} else if somePosts[indexPath.row].typeOfPost == .textPost {
let cell: TextTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "textTableViewCell") as! TextTableViewCell
} else {
print("Type of post is not link, picture, or text")
}
}
每個自定義單元格都有類似的標籤,例如標題和時間。我想設置使用相同的代碼行這些標籤,如:
cell.titleLabel.text = "Some title here"
然而,在這個例子中,我得到一個錯誤,說我使用的是未解決的標識符「細胞」,顯然是因爲我的變量被宣佈爲非全球性的。有沒有辦法解決這個問題,因爲swift是強類型的?謝謝!
不相關,但從數據源數組中檢索三次類型是不必要的昂貴。你應該使用switch語句'switch somePosts [indexPath.row] .typeOfPost {case .linkPost ...' – vadian
謝謝,這很有幫助。我對此很新,所以任何建議總是讚賞 – SomeGuy
這裏有很多重複的代碼。停止瘋狂。 – Alexander