Loroa Loroa - 3 months ago 36
Swift Question

Using segmented control to switch tableView

I'm trying to change my table view cell when the segmented control is changed here is what I have now

internal func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var returnValue = 0

switch(segmentedC.selectedSegmentIndex)
{
case 0:
returnValue = rest.count
break
case 1:
returnValue = fullMenu.count
break
default:
break

}

return returnValue
}


I have this for my
numberOfRowsInSection
and
cellForRowAtIndexPath


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("food") as! restTableViewCell
var cell2 = tableView.dequeueReusableCellWithIdentifier("fullM") as! fullmenuTableViewCell
switch(segmentedC.selectedSegmentIndex)
{
case 0:
let res: Rest!
res = rest[indexPath.row]

var img: UIImage?

if let urls = foo.imageString{
img = foodViewController.imageCache.objectForKey(urls) as? UIImage

}
dispatch_async(dispatch_get_main_queue()) {
cell.setupViews(res)

}

break
case 1:
cell2.textLabel?.text = fullMenu[indexPath.row]
break

default:
break

}
return cell
}


Also I have an
IBAction
for the segmented control

@IBAction func seg(sender: AnyObject) {

switch(segmentedC.selectedSegmentIndex)
{
case 0:
tableView.reloadData()
break

case 1:
tableView.reloadData()
break
default:
break

}

}


But when I change the segment only one cell from the
index 0
show up in the
index 1

Answer

In your cellForRowAtIndexPath you are always returning cell you are never returning cell2. Try returning cell2 in your second case.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("food") as! restTableViewCell
var cell2 = tableView.dequeueReusableCellWithIdentifier("fullM") as! fullmenuTableViewCell
switch(segmentedC.selectedSegmentIndex)
{
case 0:
    let res: Rest!
    res = rest[indexPath.row]

    var img: UIImage?

    if let urls = foo.imageString{
        img = foodViewController.imageCache.objectForKey(urls) as? UIImage

    }
    dispatch_async(dispatch_get_main_queue()) {
        cell.setupViews(res)

    }

    break
case 1:
        cell2.textLabel?.text = fullMenu[indexPath.row]
        return cell2
    break

default:
    break

}
return cell
}