Reputation: 133
I have used a tableView (myTableView) on a usual UIViewController class. I wish to use reusable cells in this tableView to save memory. I did not create separate XIB and dragged and dropped a tableView component on to the viewController.
The cells have been created with a new class HistoryTableViewCell of type UITableViewCell and this class also has an XIB.
I have also created a tableViewCell and its XIB and used the following code in the tableView(_,cellForRowAt:)
method:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "historyReuseIdentifier", for: indexPath) as! HistoryTableViewCell
cell.meetingDateLabel.text = historyArray![indexPath.section]
return cell
}
This line of code works fine with a tableViewController when I add the following line in the viewDidLoad()
method:
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "reuseIdentifier")
But the tableView.register
property cannot be used with a tableView. How do I make use of the reusable cells here?
Upvotes: 0
Views: 534
Reputation: 133
The answer was actually quite simple. I figured it out after reading a few of the other answers.
All I needed was to replace this line:
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "reuseIdentifier")
with this one:
UITableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "reuseIdentifier")
Since there is no table view by the name tableView, you need to access the UITableView class.
Upvotes: 1
Reputation: 17892
Try to create it directly in cellForRowAt indexPath:
like this. Here no need of tableView.register(UINib(nibName: "TableViewCell", ...
line.
//And replace names with your names
var cell = tableView.dequeueReusableCell(withIdentifier:"cell") as? TableViewCell
if cell == nil {
cell = Bundle.main.loadNibNamed("TableViewCell",owner: self, options: nil)?.first as? TableViewCell
}
Upvotes: -1
Reputation: 1444
Lets say your xib is ok, everything works fine and the only thing left is to register the nib
.
First declare your table view:
@IBOutlet weak var tableView: UITableView!
In the viewDidLoad()
:
tableView.register(UINib(nibName: "HistoryTableViewCell", bundle: nil) , forCellReuseIdentifier: "historyReuseIdentifier")
Also check your tableView's dataSource
and delegate
.
Upvotes: 1
Reputation: 31
Do you want to reuse the cells thats ok, to use them you need to register it first..suppose you have multiple tableView in a single ViewController, then you have to register each cell with respective tableView. just register the tableViewCell with respective tableView and use its reusableIdentifier which you have used while registering the tabelViewcell.
Upvotes: 0