Swift 4.0中比较结构体值后UITableView出现多余单元格求助
解决UITableView只显示匹配条件单元格的问题
你遇到的问题根源在于你没有过滤数据源,只是在创建单元格时跳过了不匹配项的内容赋值,但numberOfRowsInSection仍然返回了原数组的总长度,所以TableView会创建对应数量的单元格——那些不匹配的单元格就变成了空的“多余单元格”。
下面是具体的修复步骤:
1. 先过滤出符合条件的数据源
我们需要先从原数组arrayOne中筛选出cellID == cellID2的元素,把这些元素存到一个新的数组里,作为TableView的真正数据源。
2. 修改TableView的数据源方法
让numberOfRowsInSection返回过滤后数组的长度,这样TableView只会创建需要显示的单元格数量,不会出现多余的空单元格。
修改后的完整代码
import UIKit struct One { let cellID: String let name: String let lastName: String let cellID2: String } class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var arrayOne = [ One(cellID: "1", name: "hello", lastName: "hello last", cellID2: "1"), One(cellID: "1", name: "hello", lastName: "hello last", cellID2: "1"), One(cellID: "1", name: "hello", lastName: "hello last", cellID2: "2"), One(cellID: "1", name: "hello", lastName: "hello last", cellID2: "1"), One(cellID: "1", name: "hello", lastName: "hello last", cellID2: "2"), One(cellID: "1", name: "hello", lastName: "hello last", cellID2: "1") ] // 添加过滤后的数据源数组 var filteredArray: [One] = [] @IBOutlet weak var compareTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // 初始化时过滤出符合条件的元素 filterMatchingElements() compareTableView.delegate = self compareTableView.dataSource = self } // 过滤方法:筛选cellID和cellID2匹配的元素 func filterMatchingElements() { filteredArray = arrayOne.filter { $0.cellID == $0.cellID2 } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 返回过滤后的数组长度,而不是原数组 return filteredArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CompareTableViewCell") as! CompareTableViewCell let item = filteredArray[indexPath.row] // 现在所有元素都是符合条件的,直接赋值即可 cell.lblOne.text = item.cellID cell.lblTwo.text = item.cellID2 cell.lblThree.text = item.lastName cell.lblFour.text = item.name return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } }
额外说明
- 如果你的数据源
arrayOne会动态变化(比如下拉刷新、新增数据),记得每次变化后调用filterMatchingElements(),然后调用compareTableView.reloadData()刷新TableView。 - 原来的写法中,不匹配的单元格虽然没有赋值,但TableView还是会渲染出空的单元格,这就是你看到的“多余单元格”,过滤数据源后就能彻底解决这个问题。
内容的提问来源于stack exchange,提问作者Audrey Rozario
相关产品推荐
相关产品推荐

