gpt4 book ai didi

ios - UITableView 和使用 .xib 的自定义 UITableViewCell

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:54:34 25 4
gpt4 key购买 nike

在我的应用程序中,我使用了一个使用 xib 文件的自定义 tableViewCell。我创建 .xib 文件导出标签等到我的 TableViewCell 类

在我的 ViewController 中,我用来在表格 View 中填充和显示单元格的代码如下:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let transaction = statementArray[indexPath.row]
let cell = Bundle.main.loadNibNamed("StatementCell", owner: self, options: nil)?.first as! StatementCell



cell.transAmount.text = String(transaction.transAmount)
cell.transDesc.text = transaction.transDesc
cell.transFees.text = String(transaction.transFees)

return cell
}

我知道 tableView 的工作方式是重复使用离开屏幕的单元格。我加载 .xib 和填充单元格的方式是否正确?还是我必须在我的代码中添加一些东西?

最佳答案

首先你需要用 UITableView 注册你的自定义单元格

yourTableView.register(UINib(nibName: "StatementCell", bundle: nil), forCellReuseIdentifier: "cellIdentifier")

然后在 UITableView Delegate 方法 cellForRowAt 你需要写

let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! StatementCell
cell.textLabel?.text = "Sample Project"
return cell

现在您可以使用 cell.propertyName 访问您的 UITableViewCell 属性

并且您必须注意“cellIdentifier”和“forCellReuseIdentifier”的值必须相同。

关于ios - UITableView 和使用 .xib 的自定义 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43154516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com