cant return cell in cellForRowAtIndexPath

后端 未结 4 1719
北荒
北荒 2021-01-15 15:44

i\'m trying to return different cells in a tableView. Normally in this case i would return different cells and then return nil at the bottom, but in this case it gives me an

4条回答
  •  渐次进展
    2021-01-15 15:54

    You need to declare the cell before your if...then logic, then return it after. You don't have to initialize the cell if you use var:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        var cell: UITableViewCell!
    
        if indexPath.row == 0 {
            cell = tableView.dequeueReusableCellWithIdentifier("imageCell", forIndexPath: indexPath) as UITableViewCell
            // ...
        } else if indexPath.row == 1 {
            cell = tableView.dequeueReusableCellWithIdentifier("segmentCell", forIndexPath: indexPath) as UITableViewCell
            // ...
        } else if indexPath.row == 2 {
            // ...
        } 
    
        return cell
    }
    

    (Just make sure you catch all cases - if your return cell without initializing you'll get a runtime error.)

提交回复
热议问题