类型'ViewController'不符合协议'UITableViewDataSource'

Cod*_*ker 50 uitableview ios swift

开始练习快速.在singleViewController中,我试图制作一个UITableView.在storyboard中我设置了数据源和委托.这里我收到错误*'ViewController'不符合协议'UITableViewDataSource'*

错误的屏幕截图

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var table: UITableView!


    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 numberOfSectionsInTableView(tableView: UITableView!) -> Int
{
    return 20
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
    let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "mycell")
cell.textLabel.text="row#\(indexPath.row)"
    cell.detailTextLabel.text="subtitle#\(indexPath.row)"

    return cell

}
Run Code Online (Sandbox Code Playgroud)

小智 74

您应该在最后一个之前实现所有必需的方法},但是您已经在UIViewController之外编写了它们.此外,您需要更改行数的func.

建议的编辑

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var table: UITableView!


    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 20
    }

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
    {
        let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "mycell")
        cell.textLabel.text="row#\(indexPath.row)"
        cell.detailTextLabel.text="subtitle#\(indexPath.row)"

        return cell
    }
}
Run Code Online (Sandbox Code Playgroud)


aal*_*ano 16

尝试删除!在你的功能.这对我来说很重要

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "mycell")
    cell.textLabel.text="row#\(indexPath.row)"
    cell.detailTextLabel.text="subtitle#\(indexPath.row)"

    return cell
}
Run Code Online (Sandbox Code Playgroud)

  • 请解释为什么删除'!' 允许班级符合 (3认同)

sta*_*Man 10

您需要实现所有必需的方法UITableViewDataSource才能摆脱该错误.

基本上......你错过了:

func tableView(tableView:UITableView!, numberOfRowsInSection section:Int) -> Int {
    //return XX
}
Run Code Online (Sandbox Code Playgroud)