Swift中UITableView多表头实现:创建3个表头及每行8个学生
问题需求
我希望在UITableView中创建3个表头,且每行显示8个学生,以下是我的代码:
原代码
class ViewController: UIViewController { var schoolOfList: [Any] = [ [["school": ["VIP", "Bright International", "Motherland"]], [["student1": ["Chirag", "Akshay", "Shailesh", "Vishal", "Mehul", "Vinod", "Mukesh", "Darshan"]], ["student2": ["Manjari", "Kairav", "Abhimanyu", "Akshara", "Arohi", "Neel", "Naksh", "Naman"]], ["student3": ["Paritosh", "Anuj", "Kavya", "Samar", "Vanraj", "Kinjal", "Anupama", "Riyan"]]]]] @IBOutlet weak var mytableview : UITableView! override func viewDidLoad() { super.viewDidLoad() } } extension ViewController:UITableViewDelegate,UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> (Int) { return schoolOfList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:indexPath) cell.textLabel?.text = schoolOfList["school"] as! [String]indexPath.row return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerview = UIView(frame: CGRect(x:0,y:0,width:self.mytableview.frame.width,height:50)) headerview.backgroundColor = .green let lable = UILabel(frame: CGRect(x:0,y:0,width:self.mytableview.frame.width,height:50)) lable.textAlignment = .center lable.text = (schoolOfList["school"]as!String) headerview.addSubview(lable) return headerview }
代码问题分析
- 数据结构混乱:多层嵌套的
[Any]数组导致类型不安全、取值逻辑复杂,无法直接映射"学校-学生分组"的对应关系。 - 数据源方法逻辑错误:
numberOfRowsInSection返回数组长度,不符合"3个学校对应3个section,每个section下3行学生"的需求。cellForRowAt中取值语法错误,无法从数组中通过键值获取数据,类型转换逻辑也不成立。
- 表头视图实现错误:强制将数组转为String,无法正确获取学校名称,语法逻辑不成立。
修正后的实现
第一步:重构数据结构
改用结构化数据存储,明确"学校-学生分组"的对应关系:
struct SchoolInfo { let name: String let studentGroups: [[String]] } class ViewController: UIViewController { // 3个学校,每个学校对应3组8人学生列表 var schools: [SchoolInfo] = [ SchoolInfo(name: "VIP", studentGroups: [ ["Chirag", "Akshay", "Shailesh", "Vishal", "Mehul", "Vinod", "Mukesh", "Darshan"], ["Manjari", "Kairav", "Abhimanyu", "Akshara", "Arohi", "Neel", "Naksh", "Naman"], ["Paritosh", "Anuj", "Kavya", "Samar", "Vanraj", "Kinjal", "Anupama", "Riyan"] ]), SchoolInfo(name: "Bright International", studentGroups: [ ["Chirag", "Akshay", "Shailesh", "Vishal", "Mehul", "Vinod", "Mukesh", "Darshan"], ["Manjari", "Kairav", "Abhimanyu", "Akshara", "Arohi", "Neel", "Naksh", "Naman"], ["Paritosh", "Anuj", "Kavya", "Samar", "Vanraj", "Kinjal", "Anupama", "Riyan"] ]), SchoolInfo(name: "Motherland", studentGroups: [ ["Chirag", "Akshay", "Shailesh", "Vishal", "Mehul", "Vinod", "Mukesh", "Darshan"], ["Manjari", "Kairav", "Abhimanyu", "Akshara", "Arohi", "Neel", "Naksh", "Naman"], ["Paritosh", "Anuj", "Kavya", "Samar", "Vanraj", "Kinjal", "Anupama", "Riyan"] ]) ] @IBOutlet weak var mytableview: UITableView! override func viewDidLoad() { super.viewDidLoad() // 注册单元格(若通过Storyboard设置identifier可省略) mytableview.register(UITableViewCell.self, forCellReuseIdentifier: "StudentCell") mytableview.delegate = self mytableview.dataSource = self } }
第二步:实现UITableView代理与数据源方法
extension ViewController: UITableViewDelegate, UITableViewDataSource { // section数量等于学校数量(3个) func numberOfSections(in tableView: UITableView) -> Int { return schools.count } // 每个section的行数等于对应学校的学生分组数(3行) func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return schools[section].studentGroups.count } // 配置单元格:每行显示8个学生,用逗号拼接展示 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "StudentCell", for: indexPath) let targetSchool = schools[indexPath.section] let targetStudents = targetSchool.studentGroups[indexPath.row] cell.textLabel?.text = targetStudents.joined(separator: ", ") return cell } // 设置表头高度 func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50 } // 配置表头视图 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 50)) headerView.backgroundColor = .green let titleLabel = UILabel(frame: headerView.bounds) titleLabel.textAlignment = .center titleLabel.text = schools[section].name titleLabel.textColor = .white titleLabel.font = .boldSystemFont(ofSize: 16) headerView.addSubview(titleLabel) return headerView } }
补充说明
如果需要每行8个学生排版更整齐(比如分栏展示),可以自定义UITableViewCell,在cell中添加多个UILabel或嵌入UICollectionView实现布局。
内容的提问来源于stack exchange,提问作者RIYA K M
相关产品推荐
相关产品推荐

