Martin Martin - 1 month ago 8
Swift Question

How to find and set the text to UILabel of UITableViewCell in Swift?

I use

Http get
to get the
json data
and parse it.

It works fine so far and it shows the data on the
UITableView
.
I have a
UITableCell
in
UITableView
.
And the cell also has three
UILabel-s
in it like in the following picture.

enter image description here

And I have set the
Identifier
of
TableViewCell
to "Cell" like in the following picture.
enter image description here

I want to set
"AAA" , "BBB" , "CCC"
to the
UILebel-s
in
UITableViewCell
, but in the following code, I can not find any
UILabel
in
UITableViewCell
.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

cell.

return cell
}


Should I need to connect the
UILabel
to Swift file?

How to find and set the text to
UILabel
of
UITableViewCell
?

Did I missing something?

Answer

Reason why you can not access the labels in the code is that you have no connection of labels with the code, by adding labels only on the default UITableViewCell just won't work.

I suppose you are using custom UITableViewCell? if not then use a custom cell and add three labels in the code and connect them on UI as outlets and in your code you can access them by using cell.label1 and so on

  class CustomTableViewCell: UITableViewCell {

        @IBOutlet var label1:UILabel!
        @IBOutlet var label2:UILabel!
        @IBOutlet var label3:UILabel!

    }

In your main tableview class you could access them like as follows

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomTableViewCell

        cell.label1.text = "AAAA"
        return cell
    }