Joe Sloan Joe Sloan - 5 months ago 11
iOS Question

UITableViewCells displaying over cells of other types

I have 2 classes of cell in a tableView. One is sort of a title card, displaying the user's name and photo, and the ones below it are displaying 5 of the user's menu items. My configuration for this is below:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

if indexPath.row == 0{
let cell = self.menuTable.dequeueReusableCellWithIdentifier("userInfoCard", forIndexPath: indexPath) as! userInfoCard

//Load data

return cell
}else{
let cell = self.menuTable.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! menuItemCell


Here I load the various item names from their respective arrays.
Because indexPath 0 is occupied, my first menu card won't show
unless I do all of the weird resetting below with the - 1s

cell.itemName.text = self.itemNames[indexPath.row - 1]
cell.itemPrice.text = self.itemPrices[indexPath.row - 1]
cell.itemDescription.text = self.itemDescriptions[indexPath.row - 1]

return cell
}

}


I understand why the first item doesn't load, but is this the proper solution to make all of the menu items appear?

Answer

Use UITableView Sections. By this you won't that tricky manipulation

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
       return 2;
    }

Now in your cellForRowAtIndexPath method:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if indexPath.section == 0{
        let cell = self.menuTable.dequeueReusableCellWithIdentifier("userInfoCard", forIndexPath: indexPath) as! userInfoCard

        //Load data

        return cell
    }else{
        let cell = self.menuTable.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! menuItemCell

        //row starts from 0 with section 1
        // No subtraction needed
        cell.itemName.text = self.itemNames[indexPath.row]
    }