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

问题描述 投票:0回答:2

如何使用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)
}
ios swift tableview xib
2个回答
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)
}


0
投票

将此内容放入您的viewDidLoad

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

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

© www.soinside.com 2019 - 2024. All rights reserved.