简体   繁体   中英

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.

在此输入图像描述

And I have set the Identifier of TableViewCell to "Cell" like in the following picture. 在此输入图像描述

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?

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
    }

Yes, you can do this by giving every label a unique tag and then access that label in the ViewController with the tag property then your cellforRowatIndexpath will change to following code :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? CustomTableViewCell {

        if let label1 = cell.viewWithTag(1) as? UILabel { // 1 is tag of first label
            label1.text = "AAAA"
        }
        if let label2 = cell.viewWithTag(2) as? UILabel { // 2 is tag of second label
            label2.text = "BBBB"
        }
        if let label3 = cell.viewWithTag(3) as? UILabel { // 3 is tag of third label
            label3.text = "CCCC"
        }
        return cell

    }

    return UITableViewCell()
}

Hope it will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM