【问题标题】:Display three reusbale cells in tableview - Swift 5在 uitableview 中显示三个可重复使用的单元格 - Swift 5
【发布时间】:2021-08-08 16:59:39
【问题描述】:

我有 3 个带有 XIB 文件的 UITableViewCell,但在我的 tableview 上我无法显示我的三个 UITableViewCell,只能加载前两个

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (indexPath.item % 2 == 0) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CaptureNameTableViewCell", for: indexPath) as! CaptureNameTableViewCell
        cell.nameTextField.text = ""
        cell.nameTextField.tag = indexPath.row
        cell.nameTextField.delegate = self
        return cell
    } else if indexPath.section == 2 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CapturePhotoTableViewCell", for: indexPath) as! CapturePhotoTableViewCell
        cell.displayImage = imageView
        cell.cellDelegate = self
        cell.selectImage.tag = indexPath.row
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PieChartTableViewCell", for: indexPath) as! PieChartTableViewCell
        return cell
    }
}

【问题讨论】:

    标签: swift xcode tableview cell


    【解决方案1】:

    你需要在tableViewController里面注册xib tableViewCells:

    首先在单元格 xib 类中创建一个 id 属性,用作单元格的重用标识符(使其名称与您在 xib 文件中设置的单元格的重用标识符相同):

    let id = "cellIdentifier" // Name this appropriately
    

    然后在单元格的 xib 类中创建一个nib 方法:

    func nib() -> UINib {
        return UINib(named: "cellIdentifier", bundle: nil)
    }
    

    然后在viewDidLoad()这样的生命周期方法内部:

    tableView.register(nib: cell.nib, forCellReuseIdentifier: cell.id)
    

    最后,在 indexPath.row 的 table view 中指定你想要的单元格。 (表格视图中的哪一行):

    switch indexPath.row {
        case 0: // First cell
            let cell = tableView.dequeueReusableCell(withIdentifier: "CaptureNameTableViewCell", for: indexPath) as! CaptureNameTableViewCell
            // Configure cell as before
            return cell
        case 1: // Second cell
            let cell = tableView.dequeueReusableCell(withIdentifier: "CapturePhotoTableViewCell", for: indexPath) as! CapturePhotoTableViewCell
            // Configure cell as before
            return cell
        case 2: // Third cell
            let cell = tableView.dequeueReusableCell(withIdentifier: "PieChartTableViewCell", for: indexPath) as! PieChartTableViewCell
            // Configure cell as before
            return cell
        default:
            return UITableViewCell() // This should not be reached but a switch statement must cover all possibilities.
    }
    

    【讨论】:

    • 我已经这样做了,我只展示了 ID 为 CaptureNameTableViewCell 的第一个 XIB,但是其他 2 个 XIB 没有出现在表格中......
    • 希望我已经更新了我的答案,这符合您现在的预期。我认为您当前没有正确地将单元格插入到它们的行中。
    猜你喜欢
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多