通过storyboard创建tableView使用自定义tableViewCell表单xib获取断言失败

时间:2016-10-27 08:07:54

标签: ios swift uitableview

tableView创建storyboard,并在tableView delegate方法中:tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell出现异常:

*** Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:],
   /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3599.6/UITableView.m:6593

我的代码如下:

ViewController11

@IBOutlet weak var tableView: UITableView!  // tableView

// tableview delegate
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell_id: String = "cell_id"
    // this line below occurs exception: Thread 1:breakpoint 5.2
    var cell: TableViewCell2 = tableView.dequeueReusableCell(withIdentifier: cell_id, for: indexPath) as!  TableViewCell2

    if cell == nil {

        // 
    }

    var title = dataSource[indexPath.row]

    cell.titlelabel?.text = String(title)


    return cell
}

storyboard ViewController11

viewController11

xib TableViewCell2

TableViewcell12

1 个答案:

答案 0 :(得分:0)

您必须先从xib​​注册UITableViewCell才能使用它:

斯威夫特2:

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.registerNib(UINib(nibName: "TableViewCell2", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "cell_id")
}

斯威夫特3:

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.register(UINib(nibName: "TableViewCell2", bundle: Bundle.main), forCellReuseIdentifier: "cell_id")
}
相关问题