【问题标题】:Setting data source and delegate crashes the app for UITableView设置数据源和委托使 UITableView 的应用程序崩溃
【发布时间】:2017-10-02 16:46:53
【问题描述】:

这里是新的,所以请多多包涵……我有一个简单的视图控制器,其中包含一个UITableView。我不确定是否应该将数据源和数据控制器连接到视图控制器。这样做会使应用程序崩溃,但如果我不这样做,当我运行应用程序时,我不会在表格视图中看到任何输出。这应该如何工作?

class ViewController: UIViewController {    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        else {
            return 2
        }
    }

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0 {
            return "One"
        } else {
            return "Two"
        }
    }

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


        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! UITableViewCell


        let cellImage: UIImage = UIImage (named: "generic.png")!

        print("cell")

        if indexPath.section == 0 {
            cell.textLabel!.text = "Section 0, Row 0"
            cell.detailTextLabel!.text = "Detail goes here."
            cell.imageView!.image = cellImage
            print("inside cell1")
        }
        else{
            if indexPath.row == 0 {
                cell.textLabel!.text = "Section 1, Row 0"
                cell.detailTextLabel!.text = "Detail goes here."
                cell.imageView!.image = cellImage
                print("inside cell2")
            }
            else {
                cell.textLabel!.text = "Section 1, Row 1"
                cell.detailTextLabel!.text = "Detail goes here."
                cell.imageView!.image = cellImage
                print ("inside cell3")
            }
        }
        return cell
        }

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

}

【问题讨论】:

  • 你创建了tableview的outlet吗?并设置UITableviewDataSourceUITableviewDelegate
  • 仅供参考 - Swift 4 现已推出。斯威夫特 2 已经死了。是时候更新了。

标签: swift uitableview delegates swift2


【解决方案1】:

您的视图控制器需要符合UITableViewDataSourceUITableViewDelegate 才能使用这些方法。将您的类声明更改为:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多