使用UISegmentedControl切换UITableView数据源无响应如何解决
问题修复方案
核心问题是你当前的TableView数据源方法始终读取tasks数组,没有和分段控件的选中状态做绑定,点击分段后仅执行刷新但数据源没有切换,所以页面无变化。
具体修改步骤:
- 新增当前活跃数据源的计算属性,自动根据分段控件的选中状态返回对应数组
- 修改TableView数据源方法,统一读取活跃数据源
- 调整分段控件的添加方式,避免和Cell内容重叠
- 切换分段时触发数据源切换+刷新
修改后的完整代码:
class MyTasksCollectionCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource { var tasks = [Add]() var pastTasks = [Add]() // 新增分段控件属性,方便后续读取选中状态 var segmentControl: UISegmentedControl! static let identifier = "MyTasksCollectionCell" private let cellID = "CellID" // 新增当前活跃数据源计算属性,自动匹配分段选中状态 var currentTasks: [Add] { switch segmentControl.selectedSegmentIndex { case 1: return pastTasks default: return tasks } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 改成读取当前活跃数据源的长度 return currentTasks.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! MyTasksTableCell cell.accessoryType = .disclosureIndicator // 统一从currentTasks读取数据 let task = currentTasks[indexPath.row] cell.categoryLabel.text = "\(task.category)" cell.dateLabel.text = "\(task.date)" cell.hourLabel.text = "\(task.hour)" if cell.categoryLabel.text == "Urgent" { cell.categoryIcon.image = #imageLiteral(resourceName: "red.png") } else if cell.categoryLabel.text == "Important" { cell.categoryIcon.image = #imageLiteral(resourceName: "orange.png") } else if cell.categoryLabel.text == "Not Important" { cell.categoryIcon.image = #imageLiteral(resourceName: "green.png") } cell.dateIcon.image = UIImage(systemName: "calendar.badge.clock") return cell } func addControl() { let segmentItems = ["Present Tasks", "Past Tasks"] segmentControl = UISegmentedControl(items: segmentItems) // 调整分段控件的父视图为tableHeaderView,避免滚动和遮挡 let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 40)) segmentControl.frame = CGRect(x: 10, y: 5, width: (headerView.frame.width - 20), height: 30) segmentControl.addTarget(self, action: #selector(segmentControlAction(_:)), for: .valueChanged) segmentControl.selectedSegmentIndex = 0 headerView.addSubview(segmentControl) tableView.tableHeaderView = headerView } @objc func segmentControlAction(_ segmentedControl: UISegmentedControl) { // 切换分段后直接刷新即可,currentTasks会自动匹配选中状态 tableView.reloadData() } }
额外注意点:
- 需确保
pastTasks数组已经正确赋值有数据,否则切换到第二组会显示空白 - 如果你的TableView有下拉刷新等逻辑,刷新后也要分别更新
tasks和pastTasks两个数组的内容,再调用reload即可
内容的提问来源于stack exchange,提问作者Unknown
相关产品推荐
相关产品推荐

