如何在iOS 13.3上使用xib显示UITableViewCell?

时间:2019-12-18 07:23:00

标签: ios swift tableview xib

如何使用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)
}

2 个答案:

答案 0 :(得分:1)

您以错误的方式注册了Xib。只需在viewDidLoad()注册即可。 我告诉您如何Xib registering而不是您的logic

这是我的答案:

在viewDidLoad()上注册xib

tableView.register(UINib(nibName: "SurveyFacultyCell", bundle: nil), forCellReuseIdentifier: "SurveyFacultyCell")

cellForRowAt:

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

 ... Your logic ... 

return cell

完成

override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        tableView.register(UINib(nibName: "SurveyFacultyCell", bundle: nil), forCellReuseIdentifier: "SurveyFacultyCell")
    }


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

        let cell = tableView.dequeueReusableCell(withIdentifier: "surveyFacultyCell", for: indexPath) 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)
}

答案 1 :(得分:-1)

将此内容放入您的viewDidLoad

tblView.register(UINib(nibName: "SurveyFacultyCell", bundle: nil), forCellReuseIdentifier: "surveyFacultyCell") 

如果您要像这样注册一个单元格,则dequeReusableCell方法将在没有可重复使用的单元格的情况下为您创建一个单元格。 因此,您无需在cellForRow方法中检查nil单元格