Xcode 9 Swift 4 UITableView无法识别的选择器发送到实例

Alv*_*vin 2 uitableview ios swift

我刚刚从obj-c转移到swift,我在UIViewController中遇到了UITableView的问题

我已将Interface Builder中的委托和数据源从TableView设置到View Controller,但它不能正常工作

这是截图

在此输入图像描述

这是我的视图控制器

class SideMenuViewController: UIViewController {

@IBOutlet var tableView: UITableView!
var cellRow = ["Item 1","Item 2","Item 3"]

 // MARK: - TableView Delegates
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cellRow.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    let object = cellRow[indexPath.row]
    cell.textLabel!.text = object.description
    return cell
}
Run Code Online (Sandbox Code Playgroud)

这是错误

reason: '-[MyApp.SideMenuViewController tableView:numberOfRowsInSection:]: unrecognized selector sent to instance
Run Code Online (Sandbox Code Playgroud)

但是,如果我通过使用视图控制器内的代码手动设置委托和数据源,它将工作.这是一个错误?

谢谢

Bil*_*lal 11

你必须添加UITableViewDelegate,UITableViewDataSource.委托类必须告诉编译器我们正在采用该协议,然后实现委托方法.

class SideMenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    // ...    
}
Run Code Online (Sandbox Code Playgroud)

另一种好看的方式是通过使用扩展来实现协议和委托.

class SideMenuViewController: UIViewController {
    // ..        
}

extension SideMenuViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        let object = cellRow[indexPath.row]
        cell.textLabel!.text = object.description
        return cell
    }
}

extension SideMenuViewController : UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cellRow.count
    }
}
Run Code Online (Sandbox Code Playgroud)