【问题标题】:Using different cell type in different sections of iOS table view在 iOS 表格视图的不同部分使用不同的单元格类型
【发布时间】:2017-08-02 10:00:15
【问题描述】:

我正在测试如何为 UITableView 中的不同部分使用不同的单元格类型。我为此创建了一个项目。故事板如下所示:

如您所见,我插入了两个外观略有不同的原型单元。这是我的视图控制器:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet var tableView: UITableView!
    var firstSection = "first title"
    var secondSection = ["second title", "third title"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.dataSource = self
        self.tableView.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        return secondSection.count
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "first_cell", for: indexPath) as! FirstCell
            cell.title.text = self.firstSection
            return cell
        }
        else {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "second_cell", for: indexPath) as! OtherCell
            cell.title.text = self.secondSection[indexPath.row]
            return cell
        }
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0 {
            return "Section 1"
        }
        else {
            return "Section 2"
        }
    }
}

以及我的两种表格视图单元格的定义:

class FirstCell: UITableViewCell {
    @IBOutlet var title: UILabel!
}

class OtherCell: UITableViewCell {
    @IBOutlet var title: UILabel!
}

我确保在故事板中指定原型单元的类名,并设置它们的重用标识符。但是,编译后的应用程序显示了这种意外行为:

首先,不显示任何单元格。其次,在第二部分标题下,有一个灰色区域,带有一些我不知道其来源的 x 插图。我该如何解决这个问题?提前致谢。

【问题讨论】:

  • 你可能想实现func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
  • @Larme 成功了!非常感谢。

标签: ios uitableview swift3


【解决方案1】:

您可能需要设置单元格的高度。

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多