willDisplayCell delegate method Swift
Solution 1
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")
}
Solution 2
I think a better way would be:
guard let cell = cell as? TblCell else { return }
inside the willDisplayCell
David Robertson
Updated on June 13, 2022Comments
-
David Robertson about 2 years
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 thecellForRowAtIndexPath
method. And if i declare it again - i cannot access it's objects (i have anuibutton
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 theuibutton
.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!
-
David Robertson almost 9 yearsThank you, thats a very good idea. Tried it, but as the result uibutton becomes visible on every cell, except the last one - where the uilabel text is actually nil. Is it how it should work? Because i was expecting the opposite result (
-
Shamas S almost 9 yearsif you just want to hide the cell.act1, you can just do that in
cellForRowAtIndexPath
, shouldn't you? -
David Robertson almost 9 yearstried applying the same conditional in
cellForRowAtIndexPath
. gives me the same result - uibutton is visible on all cells, except the last one. -
Shamas S almost 9 yearsand you want UIButton only to be visible if cell.lblCarName.text is not empty, right?
-
David Robertson almost 9 yearsotherwise, i want it to be visible when cell is cell.lblCarName.text is empty
-
David Robertson almost 9 yearsi understood the mistake) very obvious) it's quest the !text.IsEmpty criteria. Thank you
-
Shamas S almost 9 yearstry using
if cell.lblCarName.text.isEmpty { cell.act1.hidden.false } else { cell.act1.hidden = true }