Reputation: 115
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
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
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