Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

willDisplayCell delegate method Swift

I've been working around the tableview and got stuck on the following issue.

As far as i understand the willDisplayCell delegate method should allow me to access the current cell design.
My issue is - i cannot access the instance of the custom cell, because it was separately declared in the cellForRowAtIndexPath method. And if i declare it again - i cannot access it's objects (i have an uibutton there). Or maybe i'm misunderstanding the use of this method.

Here is my code

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

//declaring the cell variable again

    var cell:TblCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! TblCell

    if let text = cell.lblCarName.text where !text.isEmpty {
        cell.act1.hidden = false
    } else {
        println("Failed")
    }
}

My goal as it is seen in the code is to access the TblCell uilabel and apply a conditional to it - if its nil - show the uibutton.

NB: My delegate and datasource is set correctly, the method is running, the app compiles, but the conditionals don't work as i've intended them to.

Thank you!

like image 736
David Robertson Avatar asked Aug 31 '15 08:08

David Robertson


2 Answers

This delegate give you the instance of the cell which will now be shown and that particular cell is actually sent in as the cell parameter. Typecast it and use the conditional.

Try this code instead.

var cell:TblCell = cell as! TblCell

if let text = cell.lblCarName.text where !text.isEmpty {
    cell.act1.hidden = false
} else {
    println("Failed")
}
like image 85
Shamas S Avatar answered Sep 20 '22 22:09

Shamas S


I think a better way would be:

guard let cell = cell as? TblCell else { return }

inside the willDisplayCell

like image 21
Matt Avatar answered Sep 21 '22 22:09

Matt