如何在 Swift 中找到并设置文本到 UITableViewCell 的 UILabel?

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

我使用 Http get 获取 json data 并解析它。

到目前为止它工作正常,它显示 UITableView 上的数据。 我在 UITableView 中有一个 UITableCell。 并且单元格中也有三个 UILabel-s 如下图所示。

并且我已经将TableViewCellIdentifier设置为"Cell",如下图所示。

我想将"AAA" , "BBB" , "CCC"设置为UITableViewCell中的UILebel-s,但是在下面的代码中,我在UITableViewCell中找不到任何UILabel .

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

        cell.

        return cell
    }

我需要将 UILabel 连接到 Swift 文件吗?

如何查找文本并将其设置为 UITableViewCellUILabel

我是不是漏掉了什么?

无法访问代码中标签的原因是标签与代码没有关联,仅在默认UITableViewCell上添加标签是行不通的。

我想您使用的是自定义 UITableViewCell?如果没有,则使用自定义单元格并在代码中添加三个标签,并将它们连接到 UI 作为插座,在您的代码中,您可以使用 cell.label1 等访问它们

  class CustomTableViewCell: UITableViewCell {

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

    }

在您的主表视图中 class 您可以按如下方式访问它们

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

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

是的,您可以通过给每个标签一个唯一的标签,然后使用标签 属性 在 ViewController 中访问该标签,然后您的 cellforRowatIndexpath 将更改为以下代码:

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()
}

希望对您有所帮助。