如何在没有Storyboard的情况下添加UITableView?(UITableView错误)

5

我使用Swift添加了一个UITableview(没有使用Storyboard),但是出现了错误,我不知道为什么。

错误信息如下:

2015-06-26 11:08:14.149 test[62289:4994907] *** 在-[UITableView dequeueReusableCellWithIdentifier:forIndexPath:]中的断言失败,/SourceCache/UIKit_Sim/UIKit-3347.44/UITableView.m:6245

2015-06-26 11:08:14.152 test[62289:4994907] *** 终止应用程序由于未捕获的异常 'NSInternalInconsistencyException',原因:'无法使用标识符TextCell取消排队单元格 - 必须为标识符注册nib或类或连接故事板中的原型单元格'

我不知道该如何解决它。

源代码如下:

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    let swiftBlogs = ["a","b","c","d"]

    let textCellIndetifier = "TextCell"

    var t = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    
        t.frame = self.view.frame
        self.view.addSubview(t)
    
        t.delegate = self
        t.dataSource = self
    
    }

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

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = t.dequeueReusableCellWithIdentifier(textCellIndetifier, forIndexPath: indexPath) as! UITableViewCell
        let row = indexPath.row
        cell.textLabel?.text = swiftBlogs[row]
        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        t.deselectRowAtIndexPath(indexPath, animated: true)
    
        let row = indexPath.row
        println(swiftBlogs[row])
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

1个回答

8

您需要注册使用的单元格,由于您没有故事板,所以需要在XIB文件中制作UITableViewCell元素。

override func ViewDidLoad(){
  super.viewDidLoad()
  self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "TextCell")
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接