Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView background colour for bottom 5 rows

I do know how to input background colours for my row, but I don't really know how I can filter it by only the bottom 5 rows are "cell.backgroundColor = UIColor.red;" whereas the rest stays the same. Appreciate those who can help me this thanks!

P.S: Sorry as my swift is quite rusty.

UITableView Controller

    import UIKit
    import FirebaseDatabase


    var postData2 = [String]()
    var postData3 = [String]()
     var tableDataArray = [tableData]()



    class ResultsController: UITableViewController {


        override func viewDidLoad() {
            super.viewDidLoad()

            ref = Database.database().reference() //set the firebase reference
            // Retrieve the post and listen for changes
            databaseHandle = ref?.child("Posts3").observe(.value, with: { (snapshot) in
                postData2.removeAll()
                postData3.removeAll()
                tableDataArray.removeAll()

                for child in snapshot.children {
                    let snap = child as! DataSnapshot
                    let key = snap.key
                    let value = String(describing: snap.value!)
                    let rating = (value as NSString).integerValue


                    postData2.append(key)
                    postData3.append(value)
                    tableDataArray.append(tableData(boothName: key, boothRating: rating))


                }
                postData2.removeAll()
                postData3.removeAll()
                let sortedTableData = tableDataArray.sorted(by: { $0.boothRating > $1.boothRating })
                for data in sortedTableData {
                    postData2.append(data.boothName)

                    let value = String(describing: data.boothRating)
                    postData3.append(value)
                }

                self.tableView.reloadData()
            })
        }

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





        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return postData2.count

        }

        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.textLabel?.font = UIFont.init(name: "Helvetica", size: 23)
            cell.textLabel?.text = postData2[indexPath.row]
            cell.detailTextLabel?.text = postData3[indexPath.row] + " ♥"
            cell.detailTextLabel?.textColor = UIColor.red;
            cell.detailTextLabel?.font = UIFont.init(name: "Helvetica", size: 23)
//        cell.backgroundColor = UIColor.red;
            return cell

        }

        override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
        {
            return 80
        }

    }

    class tableData {
        var boothName: String
        var boothRating: Int
        init(boothName: String, boothRating: Int) {
            self.boothName = boothName
            self.boothRating = boothRating
        }
}

enter image description here

like image 430
Kinja Avatar asked Jun 03 '26 15:06

Kinja


2 Answers

A simple way is to have an conditional check to see if the indexPath.row value is within the last five.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    if(indexPath.row >= postData2.count-5){
        cell.backgroundColor = UIColor.red
    }else{
        cell.backgroundColor = UIColor.white /* Remaining cells */
    }
    return cell
}
like image 70
Miket25 Avatar answered Jun 06 '26 05:06

Miket25


Some of the other answers will work - but it is nicer to use cells that have a known configuration when they are dequeued by cellForRowAt, not deal with a bunch of possible starting conditions each time you dequeue a cell. To do this subclass the UITableViewCell and override prepareForReuse(). This function will be called just before a cell is returned by dequeueReusableCell. Then cells can be set to a known starting point before you configure them. If cells could be received configured any possible way in cellForRowAt, you soon wind up with a very long function with a lot of if/else conditions.

The condition

if indexPath.row >= postData2.count - 5 {
    cell.backgroundColor = UIColor.red
}

can be used as it is, and prepareForReuse takes care of the cells not keeping any settings when they are recycled. Here's an example:

override func prepareForReuse() {
    super.prepareForReuse()
    backgroundColor = UIColor.white
}

With this one simple setting it's a wash whether you do the if/else approach or use subclassing to make the most of prepareForReuse. But as soon as you have more than one thing to set in a cell you will find it is far less complex to use this function and results in far fewer mistakes with the appearance of cells - consider what would happen if there were more than one possible color a cell could be, or there were multiple elements in the cell to be configured with multiple possible values...


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!