我有三种不同类型的自定义 UITableCell。我有一个 if 语句来设置它们:
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"
但是,在这个例子中,我收到一条错误消息,说我正在使用一个未解析的标识符“cell”,这显然是因为我的变量是非全局声明的。有没有办法解决这个问题,因为 swift 是强类型的?谢谢!
最佳答案
制定一个您的 TableViewCell 类扩展的协议(protocol),并将 cell
存储为该类型的变量。
protocol MyTableViewCell {
var titleLabel: UILabel { get }
// ...
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier: String
switch somePosts[indexPath.row].typeOfPost {
case .linkPost: identifier = "linkTableViewCell"
case .picturePost: identifier = "pictureTableViewCell"
case .textPost: identifier = "textTableViewCell"
default: fatalError("Type of post is not link, picture, or text")
}
guard let cell = self.tableView.dequeueReusableCell(withIdentifier: identifier) as? MyTableViewCell else {
fatalError("Cell isn't castable to MyTableViewCell")
}
cell.titleLabel.text = "Some title here"
// ...
}
关于ios - 如何使用 if 语句将一种类型的变量设置为特定类型的自定义 tableCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41640806/