简体   繁体   中英

How to delete tableviewcell automatically

I have an array like [1...100], and I display it in a UITableView. When I add a cell to that tableview, I want the cell before it to be deleted automatically. Is this possible? I tried many solutions, and I know how to delete a cell by using the commit editing style method, but the the cell needs be deleted automatically, not with user input.

You would have to change your model and then reload the table. Let's say, as per your example, that your table contains rows with 1 to 100 in them. Your model would look like this:

var model = [1..<100]

And in cellForRowAtIndexPath you would set the text of every cell to an item in the array. Therefore, if you update the model and reload the table view, that will "automatically" delete cells. Your adding function, which deletes the last cell before adding a new one, might look like this:

func addItem(n: Int) {
    model.removeLast()
    model.append(n)
    tableView.reloadData()
}

This allows you to manipulate the model however you want, and then update your table without having to worry about working with removing and updating cells.

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