如何从UITableViewCell的UISegmentedControl向另一cell内UICollectionView发信号
修复步骤
1. 修正视图控制器代码
你原有的cellForRowAt缺少indexPath判断逻辑,且segment切换后需要主动刷新承载CollectionView的cell:
class MyProfileTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, SegmentDelegate { // 默认选中1,你也可以保留字符串类型 var viewSelected = "1" // 替换为你实际业务中承载CollectionView的cell对应的indexPath let collectionCellIndexPath = IndexPath(row: 0, section: 1) func segmentSelected(tag: Int, type: String) { guard type != viewSelected else { return } viewSelected = type // 核心逻辑:切换选中状态后主动刷新对应cell AboutTableView.reloadRows(at: [collectionCellIndexPath], with: .none) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 替换为你实际业务中segment cell对应的判断规则 if indexPath.section == 0 && indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileSegmentTableViewCell", for: indexPath) as! ProfileSegmentTableViewCell cell.delegate = self return cell } else { // 注意:Swift类名不能以数字开头,原1_2Cell为非法命名,需改为合法类名如ProfileContentCell let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileContentCell", for: indexPath) as! ProfileContentCell cell.viewSelected = viewSelected return cell } } // 其余原有逻辑保持不变 }
2. 修正Segment所属Cell代码
规范协议命名、修复语法错误、避免循环引用:
// 协议名首字母大写,用AnyObject避免循环引用 protocol SegmentDelegate: AnyObject { func segmentSelected(tag: Int, type: String) } class ProfileSegmentTableViewCell: UITableViewCell { @IBOutlet weak var profileSegmentControl: UISegmentedControl! // 代理用weak修饰避免循环引用 weak var delegate: SegmentDelegate? @IBAction func segmentPressed(_ sender: UISegmentedControl) { profileSegmentControl.changeUnderlinePosition() let type = sender.selectedSegmentIndex == 0 ? "1" : "2" delegate?.segmentSelected(tag: sender.tag, type: type) } // 其余原有逻辑保持不变 }
3. 修正CollectionView所在Cell代码
添加属性观察自动刷新,修复原有语法错误:
class ProfileContentCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var cView: UICollectionView! // 加属性观察,值变化时自动加载对应数据刷新CollectionView var viewSelected = "1" { didSet { loadContentData() } } override func awakeFromNib() { super.awakeFromNib() cView.delegate = self cView.dataSource = self loadContentData() } private func loadContentData() { getCount.removeAll() if viewSelected == "1" { // 插入类型1对应的数据加载逻辑 print("加载类型1数据") } else { // 插入类型2对应的数据加载逻辑 print("加载类型2数据") } cView.reloadData() cView.layoutIfNeeded() } // 原有UICollectionView代理、数据源逻辑保持不变 }
实现逻辑说明
- Segment切换时通过代理通知VC更新选中状态
- VC更新状态后主动刷新承载CollectionView的对应cell
- Cell收到新的选中值后自动加载对应数据、刷新CollectionView展示
内容的提问来源于stack exchange,提问作者WhySoSerious33
相关产品推荐
相关产品推荐

