skip to Main Content

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 ?

2

Answers


  1. 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()
    
    Login or Signup to reply.
  2. 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()
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search