首页 > 解决方案 > 如何显示我的 TableView 控制器的 UILabel 文本?

问题描述

在此处输入图像描述

我在这里使用 Realm 数据库。我有一个 tableview 控制器,它有很多 UILabel,我是通过从那些 Xcode UI 元素中拖动来创建的。在这种情况下,我尝试通过设置 cell = UILabel.text 来使用数据源方法来显示 UILabel 文本。但是,Xcode 给了我一个错误,说 UILabel 没有属性“文本”,这与我从苹果纪录片中看到的不同。

我应该怎么做才能在 TableView 控制器上显示这些 UILabel 文本。如果我现在在 Xcode 上运行我的项目,所有 UILabel 文本都不会出现。

我想我可以使用以下方式来显示那些 UILabel 文本:


import UIKit
import RealmSwift

class NewIdeaCreation: UITableViewController {

    let realm = try! Realm()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return ideaTable.count ?? 1
}

// Provide a cell object for each row.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

   let cell = tableView.dequeueReusableCell(withIdentifier: "cellTypeIdentifier", for: indexPath)

   // Configure the cell’s contents.
   cell.textLabel!.text = UILabel.text[indexPath.row]

   return cell
}

标签: iosswiftuitableviewuilabel

解决方案


您不能直接访问 s 的text属性,UILabel因为它不是类属性。text是一个实例属性。您首先创建一个实例,UILabel然后设置它的text值。像这样,

let label = UILabel()
label.text = "Some text"

UITableViewCells 已经有一个UILabel被调用的实例textLabel。您可以像这样设置其text属性的值。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellTypeIdentifier", for: indexPath)

    // Configure the cell’s contents.

    // I'm assuming you have a Realm object called `Idea`
    // And `ideas` is an array of those `Idea` objects
    let idea = ideas[indexPath.row]
    cell.textLabel?.text = idea.name

    return cell
}

推荐阅读