gpt4 book ai didi

ios - 如何使用 xib 文件正确创建自定义单元格、注册并加载它?

转载 作者:可可西里 更新时间:2023-11-01 01:56:17 25 4
gpt4 key购买 nike

我要

创建自定义表格单元格并添加所有组件并注册

我做了

我在下面创建了这些文件:

enter image description here

PlaceDetailCell.xibidcustomPlaceDetailCell

enter image description here

CustomPlaceDetailCell.swift

import UIKit

class CustomPlaceDetailCell: UITableViewCell {

@IBOutlet weak var country: UILabel!
@IBOutlet weak var address: UILabel!
@IBOutlet weak var distance: UILabel!

override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}


override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

// Configure the view for the selected state
}

}

我注册

//register xib file
placesTable.register(UINib(nibName: "PlaceDetailCell", bundle: nil), forCellReuseIdentifier: "customPlaceDetailCell")

这是我的cellForRowAt

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

let cell = tableView.dequeueReusableCell(withIdentifier: "customPlaceDetailCell", for: indexPath)
as! CustomPlaceDetailCell

if places[indexPath.row]["name"] != nil {
cell.textLabel?.text = places[indexPath.row]["name"]! + " (" + distances[indexPath.row] + " miles)"
}

return cell
}

我得到了

即使应用已成功构建,当我单击该单元格时也会发生崩溃。

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key address.' *** First throw call stack:

我希望

有人可以为我提供一些指导,让我做正确的事。

最佳答案

您需要将 xib 文件自定义类设置为您将其转换为的类

let cell = tableView.dequeueReusableCell(withIdentifier: "customPlaceDetailCell", for: indexPath)
as! CustomPlaceDetailCell

因为 xib 名称似乎是 PlaceDetailCellPlaceDetailCell 并且您将其转换为 CustomPlaceDetailCell

如果你注册这个

 placesTable.register(UINib(nibName: "PlaceDetailCell", bundle: nil), forCellReuseIdentifier: "customPlaceDetailCell")

然后 xib 自定义类应该设置为 CustomPlaceDetailCell 而不是 PlaceDetailCell 这通常是预期的 xib 名称 = 它是您创建然后想要更改的类名类名

关于ios - 如何使用 xib 文件正确创建自定义单元格、注册并加载它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53103429/

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