UITableView的cellForRowAt方法满足条件时能否不返回cell?
在UITableView的cellForRowAt中能否不返回cell?
哥们儿,明确告诉你:不行!这个报错就是在提醒你,cellForRowAt方法的定义要求必须返回一个UITableViewCell实例,Swift作为强类型语言,绝对不允许你在这个函数里不返回指定类型的值。
你想通过在cellForRowAt里加条件跳过返回cell的思路本身就不对,UITableView的渲染逻辑是先通过numberOfRowsInSection确定要显示多少行,然后每一行都会调用cellForRowAt来获取对应的cell。所以正确的做法是提前在数据源层面过滤掉不需要显示的内容,而不是在创建cell的时候试图“跳过”返回。
举个具体的示例,假设你原本的数据源是一个数组,我们可以先过滤出需要显示的元素:
// 假设originalData是你的原始数据源数组 let filteredData = originalData.filter { item in // 这里写你的判断条件,比如item.isVisible == true return item.meetsDisplayCondition } // 先在numberOfRowsInSection里返回过滤后的行数 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredData.count } // 然后在cellForRowAt里直接返回对应cell,无需再做条件判断 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID", for: indexPath) as! YourCustomCell let currentItem = filteredData[indexPath.row] // 配置cell的内容 cell.titleLabel.text = currentItem.title cell.subtitleLabel.text = currentItem.subtitle return cell }
如果真的有特殊场景,你需要某个位置看起来“空着”,也别想着不返回cell——可以返回一个完全透明、高度设为0的cell,但这属于hack手段,尽量避免使用,从数据源层面处理才是更规范、更易维护的方案。
内容的提问来源于stack exchange,提问作者Richard Reis
相关产品推荐
相关产品推荐

