【问题标题】:UITableView with 3 custom cells but 1 different具有 3 个自定义单元格但 1 个不同的 UITableView
【发布时间】:2015-05-27 18:19:05
【问题描述】:

我有一个TableView,我已经为该TableView 创建了带有图像、标签..等的自定义单元格,但我希望一个单元格与其他单元格不同,它有自己的内容(单元格将从后端)。 那么如何在同一个TableView 中创建两种不同类型的单元格,以及如何排列它们,例如将一种类型的单元格放在另外两个之间?

编辑:我的 UITableView 类:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let myCell: CellTableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! CellTableViewCell

    let otherCell: OtherCellTableViewCell = tableView.dequeueReusableCellWithIdentifier("otherCell", forIndexPath: indexPath) as! OtherCellTableViewCell
    // Configure the cell...

    return myCell
}

【问题讨论】:

    标签: xcode uitableview custom-cell


    【解决方案1】:

    如果您正在使用情节提要,只需将另一个 UITableViewCell 拖到表格视图中以用作原型。给它一个唯一的子类(如有必要)。在-tableView:cellForRowAtIndexPath: 中,将您当前正在出列的单元格或这个新单元格出列。

    如果您不使用情节提要,则需要 -registerClass:forHeaderFooterViewReuseIdentifier:-registerNib:forHeaderFooterViewReuseIdentifier: 使您的其他单元格样式可用于表格视图。

    这是你的代码的修改版本,应该可以工作:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if condition {
            let myCell: CellTableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! CellTableViewCell
            // Configure the cell...
            return myCell
        }
        else {
            let otherCell: OtherCellTableViewCell = tableView.dequeueReusableCellWithIdentifier("otherCell", forIndexPath: indexPath) as! OtherCellTableViewCell
            // Configure the cell...
            return otherCell
        }
    }
    

    【讨论】:

    • 我已经在“tableView:cellForRowAtIndexPath:”中有一个自定义单元格,如果我再添加一个,会返回哪一个?检查 OP。
    • 你会得到一个你指定的reuseIdentifier。现在它是带有“myCell”标识符的那个。给另一个单元格一个不同的标识符,例如“myOtherCell”。选择单元格时,您可以在 Interface Builder 的属性窗格中指定此项。
    • 检查 OP,我编辑了函数,但现在它的行为很奇怪。当我返回一个单元格时,另一个会出现,如果我点击它,它就会变成另一个。问题是我只能退回其中一个。
    • 我已经用您发布的代码的修改版本更新了我的答案。
    • 仍然不正确,我想同时显示两个单元格,不仅如此,每种类型应该有不同数量的单元格。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    相关资源
    最近更新 更多