如果超过indexpath.row,如何在表视图中设置单元格行高?

我正在尝试使用表视图制作FAQ视图控制器,我需要在UI中进行一些修复。 这是我的FAQ VC的显示

(请忽略红线)

在此处输入图像描述

在此处输入图像描述

我们可以看到,基本上有2行高,80和160.如果行被轻敲(选中),行高将从80(黄线)扩展到160(紫线)。

我想让最后一个问题下的行高仍然是80而不是160.我试过但我不能在最后一个问题下面设置行。 这是我使用的代码

class FAQVC: UIViewController { @IBOutlet weak var retryButton: DesignableButton! @IBOutlet weak var tableView: UITableView! var FAQs = [FAQ]() var selectedIndexs: [IndexPath: Bool] = [:] override func viewDidLoad() { super.viewDidLoad() getFAQData() } } extension FAQVC : UITableViewDelegate, UITableViewDataSource { // MARK: - Table View Delegate and Datasource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return FAQs.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FAQCell") as! FAQCell cell.FAQData = FAQs[indexPath.row] return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if self.cellIsSelected(indexPath: indexPath) { return 160 } else { return 80 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let isSelected = !self.cellIsSelected(indexPath: indexPath) selectedIndexs[indexPath] = isSelected tableView.beginUpdates() tableView.endUpdates() } func cellIsSelected(indexPath: IndexPath) -> Bool { if let number = selectedIndexs[indexPath] { return number } else { return false } } } 

请将此代码放在控制器的viewDidLoad()方法中。

 YOUR_TABLE_VIEW.tableFooterView = UIView(frame: .zero) 

这将删除额外的分隔符。

最快的方法是在行高80处添加一个额外的空单元格

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return FAQs.count + 1 } 

此外,请确保对cellForRowAt方法进行更改以适应此情况:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row < FAQs.count { let cell = tableView.dequeueReusableCell(withIdentifier: "FAQCell") as! FAQCell cell.FAQData = FAQs[indexPath.row] return cell } return UITableViewCell() } 

编辑:

我刚刚读到你在最后一个单元格之后并不需要分隔符。 在这种情况下,请查看https://spin.atomicobject.com/2017/01/02/remove-extra-separator-lines-uitableview/