Xib Cell with Swift 3

I already read and saw several videos about this topic, but I can’t get it to work. Im trying to cell from xib instead of storyboard.

This is my ViewController (where I have a 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 element in the table view on the StoryBoard, but now I want to try the XIB approach.

I added the cell identifier in the XIB cell to call it using the dequeueReusableCell method.

What can i do wrong? I tried disabling the dataSource and delegate in the table view, but I got an error (and I think these are not the right steps).

+6
source share
2 answers

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 partitions:

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

First of all, you need to register your nib object.

 yourTable?.register(UINib(nibName: "yourCustomCell", bundle: nil), forCellReuseIdentifier: "cellIdentifier") 
+2
source

Source: https://habr.com/ru/post/1011735/


All Articles