Sourav Basu Roy
Sourav Basu Roy

Reputation: 115

UITableViewDataSource can't be attach to class, compilation error in swift-ios

Hi all today I'm practicing swift but got a strange compiler error when attach tableViewData source to class error message is:

" Type 'ViewController' does not conform to protocol 'UITableViewDataSource'" I can't add datasource.please solve this error.

import UIKit


class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{



    @IBOutlet var tableview: UITableView!
     var array=["cat","dog","cow"]
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5;
    }
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
         var Identifier:NSString="cellid"
        let cell: UITableViewCell=tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as UITableViewCell

        cell.textLabel?.text=array[indexPath.row];

    }
}

Upvotes: 2

Views: 384

Answers (2)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

Try this:

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    var Identifier:NSString="cellid"
    let cell: UITableViewCell=tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as UITableViewCell

    cell.textLabel?.text=array[indexPath.row];

    return cell
}

Instead of :

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
     var Identifier:NSString="cellid"
    let cell: UITableViewCell=tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as UITableViewCell

    cell.textLabel?.text=array[indexPath.row];

}

Upvotes: 1

Beslan Tularov
Beslan Tularov

Reputation: 3131

To fix the error you must implement two methods UITableViewDataSource protocol

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

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

Upvotes: 1

Related Questions