在合适的视图中识别出许多单元格

时间:2016-02-26 22:56:29

标签: ios swift didselectrowatindexpath uitableview

我想在表格视图中识别许多自定义单元格“我在故事板中构建它们”,但是我要求返回值的错误,我试图返回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 /

3 个答案:

答案 0 :(得分:1)

方法cellForRowAtIndexPath需要返回非可选的UITableViewCell,因此您必须确保在任何情况下都返回一个单元格。 return是不允许的。

代码可以简化,大多数都是冗余的。唯一的区别是标识符。

合适的解决方案是索引路径的return nil属性上的switch语句。

row

答案 1 :(得分:0)

您收到错误导致您未从该方法返回单元格。

  1. 更改您的代码,使始终返回一个单元格。
  2. 选中indexPaths时,请使用其行属性 - indexPath.row
  3. 考虑将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
}
相关问题