Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UITableView Show Different Cell Every 10th Cell

I'm trying to show a different cell after every 10 cells using two arrays: "ads" and "requests" I want my TableView to look like this:

"Request"
"Request"
"Request"
"Request"
"Request"
"Request"
"Request"
"Request"
"Request"
"Request"
"Ad"
"Request"
"Request"
...

I know how to do an ad but not how to order the cells like this using two arrays. Not at all :/ Any suggestions how to achieve that? Thanks in advance!

EDIT:

func loadAds()
    {
        Api.adApi.observeAds
        {
            (ad) in
            self.list = self.requests
            for i in stride(from: self.adInterval, to: self.requests.count, by: self.adInterval).reversed()
            {
                // not getting executed
                print("test1")
                self.list.insert(ad, at: i)
            }
            // getting executed
            print("test2")
        }
    }
like image 866
Noah Avatar asked Nov 21 '25 04:11

Noah


1 Answers

In cellForRowAt just check if indexPath.row % 10 == 0. If it does then you are on a multiple of 10. Then all you need to do is instantiate a difference cell. You'll also need to keep track of the index for the request data array and the ad data array. You can do something like this.

class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var requestIndex = 0
    var adIndex = 0

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row % 10 != 0 || indexPath.row == 0 {
            requestIndex += 1
            let cell = tableView.dequeueReusableCell(withIdentifier: "RequestCell", for: indexPath) as! RequestCell
            // configure cell with requestIndex
            // cell.imageView.image = requestDataArray[requestIndex].image
            return cell
        }
        else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "AdCell", for: indexPath) as! AdCell
            adIndex += 1
            // configure cell with adIndex
            // cell.imageView.image = adDataArray[adIndex].image
            return cell
    }
}

You could also keep track of the indices using some basic math

if indexPath.row % 10 != 0 {
    let requestIndex = indexPath.row - (indexPath.row / 10) // current indexPath - the number of adds already displayed
}
else {
    let adIndex = (indexPath.row / 10) + 1 // number of previously displayed ads plus one
}
like image 146
DoesData Avatar answered Nov 23 '25 00:11

DoesData