从Realm取数据填充TableView双分区失败,仅返回1个分区的解决方法
看起来你遇到的问题是TableView没能正确显示两个分区,大概率是数据源数组的填充或者TableView DataSource方法的实现出了问题。咱们一步步来解决:
第一步:排查数据源数组的初始化问题
你定义了allTransformersNames这个二维数组来存储两个分区的数据,但很可能在数据加载阶段,没有把autobotsNames和decepticonsNames正确添加进去。比如只添加了其中一个,或者完全没做这一步。
正确的填充方式应该是在从Realm拿到数据后,把两个派系的数组都放进二维数组:
// 假设你已经从Realm获取到数据并填充了autobotsNames、decepticonsNames allTransformersNames = [autobotsNames, decepticonsNames]
第二步:确保TableView DataSource方法正确实现
你需要完整实现这几个关键的数据源方法,保证分区数、行数和数据对应上:
// 返回分区数量,对应你定义的sections数组长度 func numberOfSections(in tableView: UITableView) -> Int { return sections.count } // 返回对应分区的行数 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return allTransformersNames[section].count } // 给每个cell填充对应的数据 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID", for: indexPath) let currentName = allTransformersNames[indexPath.section][indexPath.row] cell.textLabel?.text = currentName return cell } // 可选:给分区添加标题 func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[section] }
第三步:验证Realm数据获取是否正确
确保你从Realm中正确过滤并提取了两个派系的数据,比如假设你的Realm模型有faction字段区分派系:
let realm = try! Realm() // 查询Autobots数据并转成字符串数组 let autobots = realm.objects(Transformer.self).filter("faction == 'Autobot'") autobotsNames = autobots.map { $0.name } // 查询Decepticons数据并转成字符串数组 let decepticons = realm.objects(Transformer.self).filter("faction == 'Decepticon'") decepticonsNames = decepticons.map { $0.name } // 最后一定要把两个数组放进二维数据源 allTransformersNames = [autobotsNames, decepticonsNames]
常见坑点提醒
- 忘记把两个派系数组添加到
allTransformersNames,导致二维数组只有一个元素甚至为空 numberOfSections方法返回了固定值1,而不是sections.count或者allTransformersNames.count- Realm查询条件写错,导致其中一个派系的数组为空(这种情况分区会显示,但没有行数据)
内容的提问来源于stack exchange,提问作者Kaio Guanais
相关产品推荐
相关产品推荐

