我想在表格视图中识别许多自定义单元格“我在故事板中构建它们”,但是我要求返回值的错误,我试图返回nil和int值和单元格,但错误是相同的
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("CheefsCell", forIndexPath: indexPath) as UITableViewCell
cell.accessoryType = .DisclosureIndicator
return cell }
else if indexPath == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("BeautyCell", forIndexPath: indexPath) as UITableViewCell
cell.accessoryType = .DisclosureIndicator
return cell }
else if indexPath == 2 {
let cell = tableView.dequeueReusableCellWithIdentifier("StudentServicesCell", forIndexPath: indexPath) as UITableViewCell
cell.accessoryType = .DisclosureIndicator
return cell }
else if indexPath == 3 {
let cell = tableView.dequeueReusableCellWithIdentifier("ArtAndDesigneCell", forIndexPath: indexPath) as UITableViewCell
cell.accessoryType = .DisclosureIndicator
return cell }
else if indexPath == 4 {
let cell = tableView.dequeueReusableCellWithIdentifier("StoreCell", forIndexPath: indexPath) as UITableViewCell
cell.accessoryType = .DisclosureIndicator
return cell }
else if indexPath == 5 {
let cell = tableView.dequeueReusableCellWithIdentifier("OthersCell", forIndexPath: indexPath) as UITableViewCell
cell.accessoryType = .DisclosureIndicator
return cell }
return
}
更新:: git hub link /
答案 0 :(得分:1)
方法cellForRowAtIndexPath
需要返回非可选的UITableViewCell
,因此您必须确保在任何情况下都返回一个单元格。 1}}或return
是不允许的。
代码可以简化,大多数都是冗余的。唯一的区别是标识符。
合适的解决方案是索引路径的return nil
属性上的switch语句。
row
答案 1 :(得分:0)
您收到错误导致您未从该方法返回单元格。
indexPaths
时,请使用其行属性 - indexPath.row
。if-else
树替换为switch
。答案 2 :(得分:0)
基于@ vadian答案的另一个例子:
static let identifiers = [ "CheefsCell", "BeautyCell", "StudentServicesCell", "ArtAndDesigneCell", "StoreCell" ]
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = (indexPath.row < count) ? identifiers[ indexPath.row ] : "OthersCell"
var cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
if cell == nil {
cell = UITableViewCell() // allocate a new cell here
}
cell.accessoryType = .DisclosureIndicator
// configure your cell here
return cell
}