简体   繁体   中英

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()
        }))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM