Search code examples
swiftuitableviewxib

Cell from Xib with Swift 3


I already read and saw some videos about this subject but i can't get this to work. Im trying to a cell from a xib instead of the storyboard.

This is my ViewController (where i have the Table View).

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableView: UITableView!


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.
    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return 5
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CellTableView

        cell.test.text = "A";

        return cell;

    }

}

This is my CellTableView (the class where i have my Cell):

import UIKit

class CellTableView: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    @IBOutlet var teste: UILabel!

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

I always used the Table View Cell inside the Table View on the StoryBoard but i want to try a XIB approach now.

I added the cell Identifier on the cell XIB to call it with the dequeueReusableCell method.

What i could be doing wrong? I tried to Outlet the dataSource and the delegate of the Table View but i got an error (and i think its not the right steps).


Solution

  • You need to register your nib object.

    In viewDidLoad():

    let nib = UINib(nibName: "nameOfYourNibFile", bundle: nil)
    
    tableView.register(nib, forCellReuseIdentifier: "yourIdentifier")
    

    You also need to return the number of sections:

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