Swift中如何根据API返回数据的布尔值隐藏UITableView指定行
如何隐藏UITableView中对应
status为false的行? 要实现隐藏status为false的UITableView行,最稳妥且高效的方式是先过滤数据源,而不是尝试在单元格渲染阶段直接隐藏行(这种做法容易引发索引错位、数据不匹配的问题)。下面是具体的实现方案:
1. 创建过滤后的数据源
首先,你需要基于原始的mfsListData,筛选出status == true的元素,作为UITableView实际使用的数据源:
// 定义一个过滤后的数组,作为tableView的数据源 var filteredMfsItems: [YourModelType] = [] // 在获取到API响应数据后,执行过滤操作 if let originalData = mfsListData { filteredMfsItems = originalData.filter { $0.status == true } }
注意:将
YourModelType替换成你实际使用的数据模型类型(比如对应API响应的结构体/类)。
2. 修改TableView的数据源方法
接下来,更新UITableView的核心数据源方法,让它基于过滤后的数组来计算行数和加载单元格:
行数计算:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 返回过滤后数组的元素数量 return filteredMfsItems.count }
单元格加载:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 从过滤后的数组中获取对应位置的元素 let mfsItem = filteredMfsItems[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "SendMoneyMFSTypeTableViewCellId", for: indexPath) as! SendMoneyMFSTypeTableViewCell cell.mfsNumberLabel.text = mfsItem.mobileNumber cell.mfsNameLabel.text = mfsItem.mfs?.name cell.mfsIcon.setImageFromURl(imageUrl: mfsItem.mfs?.logo ?? "") return cell }
3. 动态更新的处理(可选)
如果后续数据源有变化(比如某些元素的status被修改),只需要重新过滤数组并刷新TableView即可:
// 重新过滤数据 filteredMfsItems = mfsListData?.filter { $0.status == true } ?? [] // 刷新表格 tableView.reloadData()
为什么不推荐用heightForRowAt设为0的方式?
这种方式虽然能让行看起来“隐藏”,但UITableView的
indexPath仍然基于原始数组,容易导致点击事件、数据绑定出现错位,而且空行仍然会占用内部布局逻辑,不如直接过滤数据源来得干净可靠。
内容的提问来源于stack exchange,提问作者Mohammad Shakhaout Hossain
相关产品推荐
相关产品推荐

