ios - 带有两个自定义单元格的 UITableView 未正确显示

标签 ios swift uitableview

我有一个分组的表格 View ,由两行组成,每行都有一个自定义表格 View 单元格。我已经建立了自定义表格 View 类和单元格标识符,并与界面生成器中的表格 View 行相关联。我的第一个表格 View 单元格看起来不错,但第二个单元格似乎与第一个单元格具有相同的属性。但是,一旦我点击第二个单元格,然后点击第一个单元格,第二个单元格就会切换到正确的单元格设计。

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 2
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("EditCellID", forIndexPath: indexPath) as! EditCell
    if indexPath.row == 0
    {
        //Do some stuff
        return cell
    }
    if indexPath.row == 1
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("DeleteCellID", forIndexPath: indexPath) as! DeleteCell
        //Do some stuff
        return cell
    }

    return cell
}

最佳答案

试试这个:

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

    if indexPath.row == 0 {
        cell = tableView.dequeueReusableCellWithIdentifier("EditCellID", forIndexPath: indexPath) as! EditCell
        // Now you can access the subclass attributes by doing : (cell as! EditCell).theAttribute
    } else {
        cell = tableView.dequeueReusableCellWithIdentifier("DeleteCellID", forIndexPath: indexPath) as! DeleteCell
    }

    return cell
}

在范围内仅创建一个单元格对象,并根据行将该对象初始化为特定 UITableViewCell 子类之一的实例。

更新:添加了有关如何访问 UITableViewCell 子类属性的注释。

关于ios - 带有两个自定义单元格的 UITableView 未正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37824772/

相关文章:

ios - iOS 中的原生动画

ios - 如何在 swift 5(iOS) 中创建虚线步骤指示器

ios - 将表添加到现有数据库 IOS sqlite

ios - 如何显示 View 覆盖另一个 View 并更改 View 大小

ios - 无法更改 UINavigationBar 提示颜色

从 firebase 快速加载图像

ios - 使用performSegueWithIdentifier从TableViewCell导航到另一个 View

swift - 将空 uitableviewcells(占位符单元格)的左侧插入设置为 0 以消除左侧填充?

swift - 根据日期过滤器清除表格 View

ios - Autolayout 动画约束不动画 subview