Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 814
Adrian Avatar asked Oct 26 '16 21:10

Adrian


2 Answers

First of all, You have to register your nib object.

yourTable?.register(UINib(nibName: "yourCustomCell", bundle: nil), forCellReuseIdentifier: "cellIdentifier")
like image 114
Prabhat Pandey Avatar answered Oct 14 '22 02:10

Prabhat Pandey


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
}
like image 43
eLwoodianer Avatar answered Oct 14 '22 02:10

eLwoodianer