Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic datasource/delegates for UITableView in swift

Tags:

swift

swift2

I need to set up different objects based on certain conditions as the datasource & delegate for table view.

But I am not able to assign tableview's datasource/delegate as it throws some errors.

Cannot assign a value of type NSObject? to a value of type UITableViewDelegate?

I did check this Q&A but this did not work.

var dataSourceDelegate:NSObject?
class RootViewController: UIViewController {
...
override func viewDidLoad() {
        dataSourceDelegate = TableDataSourceDelegate()
        // Table View
        tableView = UITableView()
        tableView!.setTranslatesAutoresizingMaskIntoConstraints(false)
        tableView!.dataSource = dataSourceDelegate 
        // Cannot assign a value of type NSObject? to a value of type UITableViewDataSource?
        tableView!.delegate = dataSourceDelegate
        // Cannot assign a value of type NSObject? to a value of type UITableViewDelegate?
        view.addSubview(tableView!)

        // Constraints
        var views:[String:UIView] = ["table":tableView!]
        var hTableConstraint = "H:|[table]|"
        var vConstraint = "V:|[table]|"
        view.addConstraintsToView([hTableConstraint, vConstraint], view: view, viewVariables: views)
    }
...
}

This is the datasource/delegate class

class TableDataSourceDelegate:NSObject, UITableViewDataSource, UITableViewDelegate {
    // MARK: Datasource

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return UITableViewCell()
    }

    // MARK: Delegates
}
like image 413
user5381191 Avatar asked Jan 31 '26 02:01

user5381191


1 Answers

NSObject? doesn't conforms to UITableViewDelegate, neither to UITableViewDataSource. You should create your protocol like

protocol GeneralDataSource: UITableViewDataSource, UITableViewDelegate {}

And then all data sources should conform that protocol.

class MyDataSource: NSObject, GeneralDataSource {
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return UITableViewCell()
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
}

Then you can use it like this

var myDataSource: GeneralDataSource?

override func viewDidLoad() {
    super.viewDidLoad()

    self.myDataSource = MyDataSource()
    self.tableView.delegate = self.myDataSource
}
like image 176
Aleš Oskar Kocur Avatar answered Feb 01 '26 17:02

Aleš Oskar Kocur