代码之家  ›  专栏  ›  技术社区  ›  ms_abc

设置数据源和委托会使UITableView的应用程序崩溃

  •  0
  • ms_abc  · 技术社区  · 7 年前

    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) {
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   glyvox    7 年前

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

    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate