Home > Blockchain >  how to limit number of rows in UITableView and then display all the rows on See All button click swi
how to limit number of rows in UITableView and then display all the rows on See All button click swi

Time:11-20

I want to limit number of rows in tableView say I want to show only 2 rows initially and if user clicks "See All" button then display all the rows. The data (array) for tableView is coming from CoreData. I have entered (saved) all the data in another ViewController, and fetching data on some another ViewController. There might be a case where data may be nil. Currently, I'm displaying all the rows just like --> return array.count, but I have no idea how to achieve my condition ?

CodePudding user response:

You just need a property to indicate whether you want to show all rows or not.

var showAllRows = false

In your numberOfRowsInSection data source method you check that value:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if showAllRows {
        return array.count
    } else {
        return min(2, array.count)
    }
}

Then your button handler needs to update showAllRows and reload the table view.

showAllRows = true
tableView.reloadData()

CodePudding user response:

Declare a boolean variable,

var showMoreRows = false

       func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            if showMoreRows {
                return array.count
            } else if array.count > 2 {
                return 2
            } else {
               return 0
        } 

On more click trigger an event like

func showMoreRowsClick() {

self.showMoreRows.toggle()
self.tableView.reloadData()

}
  • Related