Ios 我已经使用xib在swift中创建了一个表视图,但在运行应用程序时它显示了一个错误

Ios 我已经使用xib在swift中创建了一个表视图,但在运行应用程序时它显示了一个错误,ios,swift,uitableview,Ios,Swift,Uitableview,它显示了我运行应用程序时的错误。我使用xib在swift中创建了一个表视图,但它显示以下错误: NSArgumentException:'-[UIView tableView:numberOfRowsInSection:]: 已将无法识别的选择器发送到实例0x7c9a6ed0“” 确保已将数据源和委托交给UITableView import UIKit class NewOrdersViewControllers: UIViewController,UITableViewDelegate,UI

它显示了我运行应用程序时的错误。我使用xib在swift中创建了一个
表视图
,但它显示以下错误:

NSArgumentException:'-[UIView tableView:numberOfRowsInSection:]: 已将无法识别的选择器发送到实例0x7c9a6ed0“”


确保已将
数据源
委托
交给UITableView

import UIKit

class NewOrdersViewControllers: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var items = ["WE","Heart","Swift"]
    @IBOutlet var tableView:UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

        // Do any additional setup after loading the view.


    }

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

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

        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell

        cell.textLabel?.text = self.items[indexPath.row]

        return cell


    }

    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

        print("You selected cell #\(indexPath.row)!")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
您可以在“numberOfSections”中定义
numberOfRows
。用我的代码替换以下代码:

tableView.delegate = self
tableView.dataSource = self
更改为以下内容:

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

我认为您没有为恰好来自xib的tableView设置委托和数据源。这是人们在使用UITableView时经常遇到的问题。 使用以下objective-c代码的swift语法设置tableview的委托和数据源

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

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.items.count
}
这些语句应该在viewDidLoad方法中。但如果不想处理用户在单元格上的点击,则第一个语句不是必须的。为了显示信息,您必须编写第二个

如果还需要别的东西,请告诉我


干杯。

您收到的错误消息表明您已将
tableView
dataSource
属性设置为视图,而不是添加了
tableView:numberOfRowsInSection:
等方法的
viewController

numberSections的默认值为1,因此,也不必明确地返回区段的数量,如果您打算创建比示例代码更大的“为什么有些值”的话,请考虑将数据源从表视图中分离出来。还要注意的是,OP并不是在用Obj-C编写代码。。。很抱歉错误已纠正:)好。。。六羟甲基三聚氰胺六甲醚。。。我是那个回答这个问题的人,你在我的回答中写下了这一点。如果能记住自然公正的原则,我将不胜感激。。我的答案应该被提升并接受@RakeshMohan。提升是我想要的。如果我的答案对你有用,请把答案投给@LearneriOS。我是新来的。我的声誉低于15,因此我无法对您提供的答案进行投票,我想,但感谢您的宝贵反馈。您好@BR41N-FCK。。你介意删除否决票吗?因为从上述评论中,答案对OP有效,而且答案错误是误导性的|这对我来说是完美的工作。尝试clean project并重新运行它。我认为您已将tableview的IBOutlet与UIView连接起来,这就是为什么它会发生的原因。因此,请检查您在XIB中的IBOutlet连接。
self.tableView.delegate = self 
self.tableView.dataSource = self