iosswiftuitableviewcustom-celluitableviewrowaction

Can you make a TableView in a custom cell?


I have a custom TableViewCell. Inside of this, I want to put another TableView, but I'm having problems. I have something like this:

import UIKit

class ByteCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {


    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var game: UIImageView!
    @IBOutlet weak var TableView: UIView!


    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        return cell
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

}

First of all, I can't write:

tableView.delegate = self
tableView.dataSource = self

anywhere in here, so I can't modify the tableView at all.

Secondly, the TableView that does appear, doesn't have any rows, and can't be scrolled. I essentially want to make a scrollable TableView inside of a custom cell which is inside of a TableView. Is this possible?

Thanks!


Solution

  • You can absolutely put a UITableView inside UITableViewCells

    Where to put .delegate = self depends how you created the cell.

    If you created it programmatically then use override init

     override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            tableView = UITableView()
            tableView.delegate = self
            tableView.dataSource = self
        }
    

    If however your load the cell from nib or storyboard then use initWithCoder

    -(id)initWithCoder:(NSCoder *)aDecoder
    {
        self = [super initWithCoder:aDecoder];
        if (self) {
           tableView = UITableView()
           tableView.delegate = self
           tableView.dataSource = self
        }
        return self;
    }
    

    Just a note, you are setting yourself up for a bumpy road. Its entirely possible nonetheless so good luck!