如何在UITableView第0组隐藏+按钮,仅在2、3、4组显示?
解决UITableView按Section控制按钮显示的问题
嘿,这问题我之前也踩过坑!核心就是靠indexPath.section精准控制按钮的显示状态,还要注意cell复用的特性,不然滚动时按钮状态会乱跳。
直接给你调整后的cellForRowAt代码,你可以根据自己的实际情况修改:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! SchoolTableViewCell // 先执行你原本的单元格配置逻辑(比如填充数据、设置样式等) // 关键逻辑:根据section判断+按钮的显示/隐藏 // 第0组(你说的数据添加区域)隐藏按钮,其余组(对应你说的第2、3、4组)显示 cell.addButton.isHidden = (indexPath.section == 0) // 如果还没给按钮绑定点击事件,这里可以补充(记得在SchoolTableViewCell里给+按钮加IBOutlet,命名为addButton) cell.addButton.addTarget(self, action: #selector(addButtonTapped(_:)), for: .touchUpInside) // 可以给按钮设置tag或者用indexPath的哈希值,方便后续识别点击的是哪一行 cell.addButton.tag = indexPath.row return cell } // 按钮点击的处理方法(把你已实现的添加逻辑放这里就行) @objc private func addButtonTapped(_ sender: UIButton) { // 这里可以通过tag或者坐标转换拿到对应的indexPath,获取对应数据 guard let indexPath = tableView.indexPathForRow(at: sender.convert(.zero, to: tableView)) else { return } let targetData = yourDataSource[indexPath.section][indexPath.row] // 执行你已实现的添加至"Saved"数组的逻辑 }
关键注意点:
一定要在cellForRowAt里每次都设置按钮的isHidden状态!因为UITableView的cell是复用机制,要是不每次显式设置,滚动时复用的cell会保留上一次的按钮状态,导致显示错乱。另外要确保你的SchoolTableViewCell里已经正确给+按钮绑定了IBOutlet,命名和代码里的addButton一致(要是你的按钮叫别的名字,记得同步修改)。
内容的提问来源于stack exchange,提问作者Dustin Johnson
相关产品推荐
相关产品推荐

