Hi Brian,
In the lecture, I lost when you use the syntax below to assign tableview cell label.
cell.viewWithTag(1000) as? UILabel
- Why did you use optional here?
- Why did you put UILabel after as?
Joey.
Hi Brian,
In the lecture, I lost when you use the syntax below to assign tableview cell label.
cell.viewWithTag(1000) as? UILabel
Joey.
Hi @nlplaw, I believe an optional was used in case the tag returns nil and viewWithTag returns a UIView but you’d need to typecast it as a label to hold the text for your cell.
Best,
Gina
Thank you, Gina.
It makes sense to me now.
Sincerely,
Joey.
Hi @nlplaw,
when you try to get a view using a tag, there are a couple of things that can happen,
in both the cases,
let element = cell.viewWithTag(1000)
will work fine but you don’t know what type element is.
Because we need a UIlabel we could use the following code
let element:UILabel = cell.viewWithTag(1000)
However given the two scenarios above, if it is nil (not assigned) it will crash, and if it is not of type UILabel it will also crash
so in that case we use
let element = cellView.viewWithTag(1000) as? UILabel
this makes it optional and can be painful to use, so the way to use it best is
if let element = cell.viewWithTag(1000) as? UILabel {
// Do what you want with the element
element.text = "change the text"
}
this lets you work with it properly otherwise the same code would have looked like element?.text = "change the text"
cheers,
This topic was automatically closed after 166 days. New replies are no longer allowed.