【发布时间】:2019-12-18 07:23:00
【问题描述】:
如何使用 xib 显示单元格?
在 iOS 13 之前的设备上,此方法显示一个单元格,因为 iOS 13 它没有。
SurveyFacultyCell 是 .xib 自定义表格视图单元格的名称
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:SurveyFacultyCell? = tblView.dequeueReusableCell(withIdentifier: "surveyFacultyCell") as? SurveyFacultyCell
if cell == nil {
tblView.register(UINib(nibName: "SurveyFacultyCell", bundle: nil), forCellReuseIdentifier: "surveyFacultyCell")
cell = tblView.dequeueReusableCell(withIdentifier: "surveyFacultyCell") as? SurveyFacultyCell
}
cell?.selectionStyle = .none
cell?.contentView.backgroundColor = UIColor.clear
let dictFaculty = arrFaculty[indexPath.row] as! NSDictionary
print(dictFaculty)
cell?.lblName.text = dictFaculty.string(forKey: "facultyName")
print(cell?.lblName.text as Any)
}
【问题讨论】:
-
将
tblView.register...移动到viewDidLoad,在cellForRow 中不需要它 -
@Tj3n 这整个 tblView.register(UINib(nibName: "SurveyFacultyCell", bundle: nil), forCellReuseIdentifier: "surveyFacultyCell")
-
我还建议从 Storyboard 或
SurveyFacultyCell(awakeFromNib()) 中设置selectionStyle和contentView.backgroundColor。将其设置为cellForRowAt不是一个好主意 -
在创建单元格的实例时,请使用
as! SurveyFacultyCell而不是as? SurveyFacultyCell,因为如果单元格类型不存在(这不应该发生,因为它应该就在那里),你的程序应该会崩溃 -
您好像忘记归还手机了。在语句末尾添加返回单元格