If I uncomment
tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?)
I get an error on the line
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
that says UITableView? does not have a member named 'dequeueReusableCellWithIdentifier'
If I unwrap the tableview then the error goes away, but in Objective-C we would normally check whether or not the cell exists, and if it does not we create a new one. In Swift, since the boilerplate provided uses the let
keyword and unwraps an optional, we can't reassign it if it's nil.
What's the proper way to use dequeueReusableCellWithIdentifier in Swift?
dequeueReusableCellWithIdentifier: Returns a reusable table-view cell object after locating it by its identifier.
This method dequeues an existing cell if one is available or creates a new one using the class or nib file you previously registered. If no cell is available for reuse and you didn't register a class or nib file, this method returns nil .
The right way to do this is to configure the prepareForReuse() method inside the NewsCell class. override func prepareForReuse() { super. prepareForReuse() imageView. image = //Default image //Whatever other things you need cleared. }
When the new cells appearing from the bottom need to be drawn they are dequeued from the reuse queue instead of initialising new instances, thereby keeping memory usage down. This is also why it's important that you configure the properties of your cell outside of the if (cell == nil) condition.
You can implicitly unwrap the parameters to the method and also cast the result of dequeueReusableCellWithIdentifier
to give the following succinct code:
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell //configure your cell return cell }
If the cell type hasn't been registered with the table view before the table loads, you can use the following to fetch a cell instance:
private let cellReuseIdentifier: String = "yourCellReuseIdentifier" // MARK: UITableViewDataSource func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) if (cell == nil) { cell = UITableViewCell(style:UITableViewCellStyle.Subtitle, reuseIdentifier:cellReuseIdentifier) } cell!.textLabel!.text = "Hello World" return cell! }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With