Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift : Clear UITableView Cells

I have an variable to store objects of a custom Class which I've loaded into a UITableView.

I'm giving the user an option to clear everything out. When this runs I'm clearing the array that stores all the players but how do I clear the TableView?

I've tried tableView.reloadData() but it doesn't do anything.

Custom Class & Global Variable:

var players: [AnyObject] = []
Class Player{
    var playerName: String?

    init(name:String){
        playerName = name
    }
}

Custom Cell cellForRowAtIndexPath:

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

    let cell: CustomMainCell = tableView.dequeueReusableCellWithIdentifier("CustomMainCell") as CustomMainCell
    // Get Player
        let thisPlayer:Player = players[indexPath.row] as Player

        cell.nameLabel?.text = thisPlayer.playerName
    }

    return cell
}

Settings Clear Function:

alertController.addAction(UIAlertAction(title: "Clear Players?", style: .Default, handler: { (action: UIAlertAction!) in
            players.removeAll()
            self.tableView.reloadData()
        }))
like image 787
vmitchell85 Avatar asked Dec 12 '22 01:12

vmitchell85


1 Answers

Clearing the array before calling tableView.reloadData() should work.

I assume your numberOfRowsInSection: and cellForRowAtIndexPath: are also using the array data to return the correct values/objects.

like image 191
trevorj Avatar answered Dec 29 '22 19:12

trevorj