NelbeDG
NelbeDG

Reputation: 445

How to build a Table View with specific number of rows?

I have been reading similar questions and until now neither has solved this error or I have not found it.

I have a TableView and I need the table to have a specific number of rows.

Now it works with a count of notifications from a array. In this array, I keep the notifications that come from the server. But I want that if this array count is greater than 40, the rows are 40 and they not are the count of the array.

This is my code:

class ClassName: UITableViewController, UITabBarControllerDelegate {
    public var notifications: [APINotification] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tabBarController?.delegate = self
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 140
    }

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

    override func viewDidAppear(_ animated: Bool) {
        self.notifications = []
        self.getLastNotifications()
        APIAuth.shared.count_badge = 0
        self.tabBarController?.tabBar.items![0].badgeValue = nil
    }

    public func getLastNotifications() {
        let req = Notification()
        req.getLastNotifications(onComplete: {events in
            self.notifications = events

            DispatchQueue.main.async(execute: {
                self.tableView.reloadData()
            })
        })
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.notifications.count
    } 

    // There is just one row in every section
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    // Set the spacing between sections
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let event = self.notifications[indexPath.section]
        let cell = tableView.dequeueReusableCell(withIdentifier: "controller", for: indexPath) as! Controller

        cell.bodyLbl.text = event.description
        cell.typelbl.text = event.type
        cell.typelbl.sizeToFit()
        cell.titleLbl.text = event.title
        cell.subjectLbl.text = event.subject?.name

        return cell
    } }

Thanks for your help!

Upvotes: 0

Views: 654

Answers (4)

Upholder Of Truth
Upholder Of Truth

Reputation: 4711

There are several ways to achieve this:

  1. Simple and consice:

    return min(self.notifications.count, 40)
    
  2. A Swifty approach:

    guard self.notifications.count < 40 else {
        return 40
    }
    
    return self.notifications.count
    
  3. An alternative more verbose version:

    return self.notifications.count < 40 ? self.notifications.count
    
  4. A different more simple version:

    if self.notifications.count > 40 {
        return 40
    } else {
        return self.notifications.count
    }
    

Use which ever version you feel best suits the purpose.

I would probably go for 1 or 2 if I felt like being all Swifty (is that even a word).

Upvotes: 3

Andreas Oetjen
Andreas Oetjen

Reputation: 10199

To limit the maximum number of sections, just check the array size:

override func numberOfSections(in tableView: UITableView) -> Int {
    var count = self.notifications.count
    if (count > 40) {
        count = 40
    }
    return count
} 

Upvotes: 1

Greg
Greg

Reputation: 25459

You can change this method to :

override func numberOfSections(in tableView: UITableView) -> Int {
    return self.notifications.count > 40 ? 40 : self.notifications.count
}

This will show as many rows as you got from your notification but if it's greater than 40 it will display only 40. To make it display 40 all the time just put return 40 instead but this may crash your app it the array will contain less items than 40.

Ps you display 40 sections no rows to change it to rows instead you need to chance your code to:

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.notifications.count > 40 ? 40 : self.notifications.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let event = self.notifications[indexPath.row]
    ...
}

Upvotes: 6

Sarabjit Singh
Sarabjit Singh

Reputation: 1824

Try the following code:

// There is just one row in every section
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if self.notifications.count > 40{
         return 40
    }
    return self.notifications.count
}

Upvotes: 2

Related Questions