Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add a UItableview without storyboard? (UITableView error )

I use swift add an UITableview (without storyboard), but an error happened , I don't why

The error is

2015-06-26 11:08:14.149 test[62289:4994907] *** Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-3347.44/UITableView.m:6245

2015-06-26 11:08:14.152 test[62289:4994907] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier TextCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

I don't know how to figure it out

The source is :

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.
    }


}
like image 539
Mofei Zhu Avatar asked Jun 26 '15 03:06

Mofei Zhu


People also ask

What is UITableView in Swift?

A view that presents data using rows in a single column. iOS 2.0+ iPadOS 2.0+ Mac Catalyst 13.1+ tvOS 9.0+

What is Indexpath in Tableview Swift?

Index paths describe an item's position inside a table view or collection view, storing both its section and its position inside that section.


1 Answers

You need to register the cell you're using, since you don't have a storyboard, you need to make a UITableViewCell element in a XIB file.

override func ViewDidLoad(){
  super.viewDidLoad()
  self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "TextCell")
}
like image 198
Rob Contreras Avatar answered Sep 20 '22 16:09

Rob Contreras