Beginning TableView 6. IndexPaths

Hi Brian,

In the lecture, I lost when you use the syntax below to assign tableview cell label.
cell.viewWithTag(1000) as? UILabel

  1. Why did you use optional here?
  2. Why did you put UILabel after as?

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.

1 Like

Hi @nlplaw,
when you try to get a view using a tag, there are a couple of things that can happen,

  1. There is no element that has the tag you are seeking
  2. You are expecting a UILabel with that tag, however accidentally you set that tag to a UIButton

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.