具有iOS的可重用tableview的二级设置菜单

时间:2018-11-02 04:04:49

标签: ios swift uitableview code-reuse

我对iOS App开发非常陌生,需要一些帮助。我正在尝试实现一种设置类型的屏幕,其中某些项目将在下一个屏幕中显示更多选项。现在尝试嵌套两个级别的设置。

我正在尝试使用UITableView,但无法重用它来显示下一级别的选项。我试图避免在此处重写相同的代码。

有人对此有建议吗?谢谢。

以下是代码:

class SettingsMenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var Options = ["Settings1", "Settings2", "Settings3" ]


    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Options.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel!.text = Options[indexPath.row]
        cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath)
        switch cell?.textLabel?.text {
        case "Settings1"?:
        //On selecting this option, need to load new set of setting options which are relevant to Settings1 but want to reuse the tableView available here

        case "Settings2"?:


        case "Settings3"?:


        case "Settings4"?:



        default:

        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果您想重用代码,则应在didSelectRowAt表上使用Settings值推送SettingsMenuViewController对象(新对象不是self),

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)
    switch cell?.textLabel?.text {
    case "Settings1"?:
       let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SettingsMenuViewController") as! SettingsMenuViewController
       vc.Options = ["Settings5","Settings6"]
       self.navigationController?.pushViewController(vc, animated: true)

    case "Settings2”?:


    case "Settings3”?:


    case "Settings4”?:



    default:

    }
}

答案 1 :(得分:0)

似乎您正在尝试使用相同的tableView来显示设置页面的两个级别。

更改数据源将始终更新单元格内容。因此,您可以使用它来模拟表中以下位置的更改:

optional func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)

只需将上述委托方法中的数据源更改为适当的数据源即可。 (确保新的数据源对象与您在 func tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath)-> UITableViewCell 中访问它们的方式兼容