ios - 如何显示我的 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
}
解决方案
您不能直接访问 s 的text
属性,UILabel
因为它不是类属性。text
是一个实例属性。您首先创建一个实例,UILabel
然后设置它的text
值。像这样,
let label = UILabel()
label.text = "Some text"
UITableViewCell
s 已经有一个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
}
推荐阅读
- python - apache_beam (python SDK) 是否支持 .zip 压缩类型
- c# - 如何从 Entity Framework Core 获取实体保存顺序
- excel - 从模板和 Excel 自动创建配置
- python - “CreateDC 失败,屏幕尺寸信息可能不正确”
- stripe-payments - Stripe 订阅 webhook 缺少元数据和 client_reference_id
- push-notification - 未从clevertap 推送控制台收到华为推送工具包消息
- php - 在 Laravel 中以一对多多态关系从数据库中获取数据的问题
- c++ - 为什么(Qt 5.15.2)STL 风格的反向迭代器不能用于从头到尾的打印?
- javascript - Jquery Datepicker、字符串连接和#selector
- python - 如何在python中使用迭代器作为变量名?