Swift:根据Segue标识符隐藏TableView指定分区
实现方案
步骤1:在ViewControllerTwo中添加状态标记
首先在ViewControllerTwo里定义枚举区分显示模式,再添加变量接收跳转时的状态:
import UIKit class ViewControllerTwo: UIViewController { // 定义两种显示模式 enum DisplayMode { case items // 仅显示第1分区 case menu // 仅显示第2分区 } var displayMode: DisplayMode = .items // 默认显示items模式 var dataArray = [["a", "b", "c"], ["menu 1", "menu 2", "menu 3"]] // 其他现有代码... }
步骤2:修正ViewController的跳转逻辑
先修正按钮动作的拼写错误,添加Segue跳转代码,再通过prepare(for:sender:)传递显示状态:
import UIKit class ViewController: UIViewController { @IBOutlet weak var itemsButton: UIButton! @IBOutlet weak var menuButton: UIButton! override func viewDidLoad() { super.viewDidLoad() itemsButton.round() menuButton.round() // 修正原代码重复调用itemsButton.round()的问题 } @IBAction func itemsButtonAction(_ sender: Any) { performSegue(withIdentifier: "segueItemsOption", sender: self) } @IBAction func menuButtonAction(_ sender: Any) { performSegue(withIdentifier: "segueMenuOption", sender: self) } // 传递显示状态到目标控制器 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let vcTwo = segue.destination as? ViewControllerTwo else { return } switch segue.identifier { case "segueItemsOption": vcTwo.displayMode = .items case "segueMenuOption": vcTwo.displayMode = .menu default: break } } }
步骤3:修改ViewControllerTwo的数据源方法
根据displayMode动态返回分区、行数据和标题,实现隐藏对应分区的效果:
extension ViewControllerTwo: UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { // 无论哪种模式都只渲染1个分区 return 1 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch displayMode { case .items: return "Section 1" case .menu: return "Section 2" } } func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { switch displayMode { case .items: return "Number of items in section 1 is \(dataArray[0].count)" case .menu: return "Number of items in section 2 is \(dataArray[1].count)" } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch displayMode { case .items: return dataArray[0].count case .menu: return dataArray[1].count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "singleCell") if cell == nil{ cell = UITableViewCell(style: .default, reuseIdentifier: "singleCell") cell?.accessoryType = .detailButton } // 根据显示模式取对应数据 let rowData = displayMode == .items ? dataArray[0][indexPath.row] : dataArray[1][indexPath.row] cell!.textLabel?.text = rowData return cell! } }
补充说明
- 原代码中
ViewController的按钮动作存在拼写错误(itesmButtonAction应为itemsButtonAction),且缺少performSegue调用,已一并修正。 - 这种实现方式是通过控制数据源返回的内容来"隐藏分区",而非直接隐藏已存在的分区,更符合UITableView的数据源逻辑。
内容的提问来源于stack exchange,提问作者Emilio CG
相关产品推荐
相关产品推荐

