ios insert more table cell rows after last index

uitableview insert row at index swift
uitableview insert row at top swift
uitableview - insert row at bottom swift
uitableview add row dynamically swift
ios uitableview insert cell
insert row in table view
insert new row swift
swift 4 uitableview add row

I'm trying to make an unlimited scroll table view(feed). However, I can't get the tableview to insert more cells after the initial load.

My table has two types of cells. A collection view table cell and a regular image+label table cell. The collection view is shown only once and it's first.

Area that is giving me issues. It does at least call, it just doesn't add any more cells. Also, not sure how it knows which type of cell to add.

extension FeedViewController: UITableViewDelegate{
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let lastElement = venueData.count
        if indexPath.row == lastElement {
            // handle your logic here to get more items, add it to dataSource and reload tableview
            print(venueData.count)
            print("last")
            if(firstLoad){
                firstLoad = false
                return
            }
            let appendAmount = 10
            currentOffset = currentOffset+appendAmount

            let res = venueDataRequest(query:"Any",offset:10,amount:appendAmount)
            venueData.append(contentsOf: res )


            self.feedTableView.beginUpdates()
            self.feedTableView.insertRows(at: [IndexPath(row: venueData.count-appendAmount, section: 0)], with: .automatic)
            self.feedTableView.endUpdates()


        }
    }
}

Full Class

import UIKit

class FeedViewController: UIViewController {

    @IBOutlet weak var feedTableView: UITableView!


    let popularPlaces = getPopularPlaces()
    var firstLoad = true
    var currentOffset = 0
    var venueData = venueDataRequest(query:"Any",offset:0,amount:10)
//    var venueData: [FeedVenueData] = []


    override func viewDidLoad() {
        super.viewDidLoad()
        feedTableView.dataSource = self
        feedTableView.delegate = self
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension FeedViewController: UITableViewDelegate{
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let lastElement = venueData.count
        if indexPath.row == lastElement {
            // handle your logic here to get more items, add it to dataSource and reload tableview
            print(venueData.count)
            print("last")
            if(firstLoad){
                firstLoad = false
                return
            }
            let appendAmount = 10
            currentOffset = currentOffset+appendAmount

            let res = venueDataRequest(query:"Any",offset:10,amount:appendAmount)
            venueData.append(contentsOf: res )


            self.feedTableView.beginUpdates()
            self.feedTableView.insertRows(at: [IndexPath(row: venueData.count-appendAmount, section: 0)], with: .automatic)
            self.feedTableView.endUpdates()


        }
    }
}

extension FeedViewController: UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1+venueData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if(indexPath.row == 0){
            let cell = tableView.dequeueReusableCell(withIdentifier: "FeedPopularPlaceCollectionViewTableViewCell", for: indexPath) as! FeedPopularPlaceCollectionViewTableViewCell
            cell.setup()
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "FeedVenueTableViewCell", for: indexPath) as! FeedVenueTableViewCell

            let pos = indexPath.row - 1
            cell.venueName.text = venueData[pos].name
            cell.venueImage.image = venueData[pos].image

            print(indexPath.row)
            return cell
        }
    }

}

The problem is because you add 10 items but only insert 1 cell. After first time called, if indexPath.row == lastElement will never reached again because indexPath.row = 1 and lastElement = 10.

To fix it, instead of inserting only 1 cell, insert 10 cells after adding new items and call insertRows on main queue

var indexPaths = (venueData.count-appendAmount+1..<venueData.count+1).map { IndexPath(row: $0, section: 0) }
DispatchQueue.main.async {
    self.feedTableView.insertRows(at: indexPaths, with: .automatic)
}

swift - ios insert more table cell rows after last index, The problem is because you add 10 items but only insert 1 cell. After first time called, if indexPath.row == lastElement will never reached again because  iOS provides three styles of table: plain, grouped, and inset grouped. Plain. Rows can be separated into labeled sections, and an optional index can appear vertically along the right edge of the table. A header can appear before the first item in a section, and a footer can appear after the last item.

You can use this code to insert more rows, when user comes to last cell.

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    //Bottom Refresh
    if scrollView == feedTableView {
        if ((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height) {
            //Insert Row in Tableview
        print(venueData.count)
        print("last")
        if(firstLoad){
            firstLoad = false
            return
        }
        let appendAmount = 10
        currentOffset = currentOffset+appendAmount

        let res = venueDataRequest(query:"Any",offset:10,amount:appendAmount)
        venueData.append(contentsOf: res )


        self.feedTableView.beginUpdates()
        self.feedTableView.insertRows(at: [IndexPath(row: venueData.count-appendAmount, section: 0)], with: .automatic)
        self.feedTableView.endUpdates()

        }
    }
}

ios insert more table cell rows after last index, I'm trying to make an unlimited scroll table view(feed). However, I can't get the tableview to insert more cells after the initial load. My table has two types of cells. If a table has multiple <tbody> elements, by default, the new row is inserted into the last <tbody>. To insert the row into a specific <tbody>: let specific_tbody = document.getElementById(tbody_id); let row = specific_tbody.insertRow(index)

At this line

 self.feedTableView.insertRows(at: [IndexPath(row: venueData.count-appendAmount, section: 0)], with: .automatic)

why you insert at index venueData.count-appendAmount

self.feedTableView.insertRows(at: [IndexPath(row: venueData.count, section: 0)], with: .automatic)

insertRows(at:with:), Inserts rows in the table view at the locations identified by an array of index paths, the kind of animation to perform when inserting the cell or requests no animation. of rows or sections until after it has handled the deletions of rows or sections. For more on this subject, see Batch Insertion, Deletion, and Reloading of  Table views on iOS display a single column of vertically scrolling content, divided into rows. Each row in the table contains one piece of your app’s content. For example, the Contacts app displays the name of each contact in a separate row, and the main page of the Settings app displays the available groups of settings.

Inserting and Deleting Rows and Sections, Table View Programming Guide for iOS Navigating a Data Hierarchy with Table Views A Closer Look at Table View Cells Inserting and Deleting Rows and Sections iOS. NextPrevious discusses how you can insert and delete multiple sections and rows Insert row at index 1 of section at index 1. Table.InsertRows(table as table, offset as number, rows as list) as table About. Returns a table with the list of rows, rows, inserted into the table at the given position, offset. Each column in the row to insert much match the column types of the table. Example 1. Insert the row into the table at position 1.

Everything you need to know about iOS UITableView, is more meaningful and easy to work with, rather than this: next cell index will become indexPath.row — 2 , after some further So separate your table into sections — so your row index would be always between 0 and items.count. So whenever you replace/remove/add new cell types — compiler will  If the number of the row to delete, specified by the parameter, is greater or equal to the number of available rows, or if it is negative and not equal to the special index -1, representing the last row of the table, the exception INDEX_SIZE_ERR is thrown. Example. This example uses JavaScript to delete a table's second row. HTML

iOS: How to build a Table View with multiple cell types, There are Table Views with the static cells, where the number of the cells and the cell in different projects: configuring the cell based on its index in UITableView. First, create a new project, add a TableView to default ViewController, pin the the last two can have multiple cells depending on the content of our JSON file. I have a simple cell reference in one of my cells down a column e.g.:"=H6", “=H7” etc. When I insert a row in Excel and copy formulas from row above, the cell reference in 'Opening Stock' does not update automatically in the row after the new blank row (should be equal to previous row balance, which is 60 now).

Comments
  • What is the issue you have got, if statement isn't called or it's called but cell isn't inserted?
  • statement is called and it runs, it just doesn't insert any rows.
  • When you call print(venueData.count), does it have different value each time?
  • @trungduc the first time it says 10 and then won't display from there. So data is being appended to the array
  • Try adding the new data in didEndDisplayingCell instead of willDisplayCell method. willDisplayCell method tells that tableview is already in the mode of editing and is not finished yet.
  • What happens after you try my code? Were any cell inserted?
  • No, unfortunately. I tried self.feedTableView.reloadData() and that seems to be working, but would still like to know why it isnt working with insert
  • I have updated my answer, you can try it again. It should be venueData.count-appendAmount+1
  • unfortunately that's not doing anything either :/
  • @TrevorWood Updated my answer. Call insertRows in main queue resolve problem
  • Take a look at numberOfRowsInSection method