Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift protocol with uitableviewdatasource [duplicate]

Tags:

ios

swift

I want to reuse the code below

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

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

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

I define a protocol :

protocol ConfigDetail: class, UITableViewDataSource{}

extension ConfigDetail{

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

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

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

}

but when i use the protocol with a UIViewController, it always tells me i did not conform to protocol UITableViewDataSource, or i have to add @objc before my protocol. But i have struct variables defined in my protocol, @objc may not help. Any solutions?

like image 413
jhd Avatar asked Jun 21 '26 18:06

jhd


1 Answers

If you want to implement these data source methods and reuse them, just define a data source class that implements them. And then rather than implementing the delegate methods in the view controller, instantiate a data source object, keep a strong reference to it, and specify it as the data source for the table view.

For example:

class DataSource: NSObject, UITableViewDataSource {

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

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        // configure cell here
        return cell
    }
}

class ViewController: UITableViewController {

    let dataSource = DataSource()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = dataSource
    }

}
like image 80
Rob Avatar answered Jun 24 '26 12:06

Rob



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!