-2

I am trying to put Ads totally randomly between cells inside a UITableView. I am gonna show my main file to you understand what I am doing and how I want: Randomly Ads

Table View Controller:


class Page1: UITableViewController, UISearchBarDelegate {
    
    @IBOutlet weak var searchBar: UISearchBar!
    var employeesSearching = [Employee]()
    var isSearching : Bool = false
    
    @IBOutlet weak var GoogleBannerView: GADBannerView!

    let collation = UILocalizedIndexedCollation.current()
    var sections: [[Any]] = []
    var objects: [Any] = [] {
        didSet {
            let selector: Selector = #selector(getter: UIApplicationShortcutItem.localizedTitle)
            sections = Array(repeating: [], count: collation.sectionTitles.count)
            let sortedObjects = collation.sortedArray(from: objects, collationStringSelector: selector)
            for object in sortedObjects {
                let sectionNumber = collation.section(for: object, collationStringSelector: selector)
                sections[sectionNumber].append(object as AnyObject)
            }
            self.tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.searchBar.delegate = self
        self.tableView.contentOffset = CGPoint(x: 0, y: searchBar.frame.height) //hide searchBar
        
        Shared.instance.employees.sort {
            (first, second) in
            first.name.compare(second.name, options: .diacriticInsensitive) == .orderedAscending
        }
    }
    
    func getMatches(letter: String, withArray array: [Employee]) -> [Employee] {
        return array.filter({ ($0.name.compare(letter, options: .diacriticInsensitive, range: $0.name.startIndex..<$0.name.index($0.name.startIndex, offsetBy: 1), locale: nil) == .orderedSame)})
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        if isSearching { return 1 }
        return collation.sectionTitles.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let letter = collation.sectionTitles[section]
        if isSearching {
            return employeesSearching.count
        } else {
            let matches = getMatches(letter: letter, withArray: Shared.instance.employees)
            if !matches.isEmpty { return matches.count }
        }
        return 0
    }
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if isSearching { return nil }
        let letter = collation.sectionTitles[section]
        let matches = getMatches(letter: letter, withArray: Shared.instance.employees)
        if matches.count == 0 { return nil }
        return collation.sectionTitles[section] }
    
    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        if isSearching { return nil }
        return collation.sectionIndexTitles }
    
    override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return collation.section(forSectionIndexTitle: index) }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 3 || indexPath.row == 9 || indexPath.row == 14 {
            let cellAd = tableView.dequeueReusableCell(withIdentifier: "cellAd", for: indexPath)
        
            GoogleBannerView?.adUnitID = "ca-app-pub-6043248661561548/4628935113"
            GoogleBannerView?.rootViewController = self
            GoogleBannerView?.load(GADRequest())
        
            return cellAd
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell1
        if isSearching {
            cell.nameLabel.text = employeesSearching[indexPath.row].name
            cell.positionLabel.text = employeesSearching[indexPath.row].position
        } else {
            let letter = collation.sectionTitles[indexPath.section]
            let matches = getMatches(letter: letter, withArray: Shared.instance.employees)
            
            cell.nameLabel.text = matches[indexPath.row].name
            cell.positionLabel.text = matches[indexPath.row].position
        }
        return cell
    }
    ...
}

How do I smuggle a UITableViewCell as! AdCell randomly into the UITableView?

I mean, what should I do in cellForRowAt? I am a bit confused between all these indexed sections.

ARNON
  • 1,097
  • 1
  • 15
  • 33
  • 3
    Showing all your files does not, in general, help people understand. Instead, it forces them to read through a wall of text in order to figure out what might be causing the errors you're seeing. In general, you should try to figure out yourself which are the relevant parts of your code and add only those to your question. See [How to create a Minimal, Complete and Verifiable example](https://stackoverflow.com/help/mcve). – Pedro Castilho May 03 '17 at 18:17
  • Thanks @PedroCastilho, I just edited my question and made it simple! :) – ARNON May 03 '17 at 18:21
  • 2
    You haven't posted a question. You've posted a statement of need and some code. Please [edit] your "question" so it is an actual question. What exactly do you need help with? What issues are you having with the code you posted? – rmaddy May 03 '17 at 18:27
  • @rmaddy, is that ok now? – ARNON May 03 '17 at 18:32

2 Answers2

2

One approach would be to insert some sort of "ad" object at desired locations within your data model.

Then update cellForRowAt to look at the object in the data model for the given index path. If it's an "ad" object, create and setup an "ad" cell. Otherwise create and setup an appropriate data cell as you do now.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Really? I know, I made a clearly question and edited twice like you guys asked. I wanna know what do I have to do on `tableView.dequeueReusableCellWithIdentifier `. [Please read](http://stackoverflow.com/help/how-to-answer) – ARNON May 03 '17 at 18:45
  • I just told you what to do. What part of my answer don't you understand? – rmaddy May 03 '17 at 18:53
2

Firstly you need to generate a random number between 0 and your tableView Datasource array size

let lower : UInt32 = 0
let upper : UInt32 = array.count
let randomIndex = arc4random_uniform(upper - lower) + lower

then you need to add the Ad object in the array at the randomIndex

array.insert(AdObject, atIndex:randomIndex)

then just reload your tableView and handle the different types in cellForRow function

  • Thanks, now about the Ads inside cellForRowAt. When I put `@IBOutlet weak var GoogleBannerView: GADBannerView!` and link to `Main.Storyboard` I had an error. I just updated my question to you see. – ARNON May 05 '17 at 22:57