【问题标题】:What is the best way to pass data in a hierarchical structure? Swift以分层结构传递数据的最佳方式是什么?迅速
【发布时间】:2015-11-09 16:37:59
【问题描述】:

所以我正在开发一个应用程序,它有几个表格视图,可以将您带到详细视图,并且该详细视图可以将您带到地图视图或 web 视图,这是我的意思的一个示例:

我没有制作几个详细信息组(详细信息、网络、地图),而是制作所有表格视图,带您到同一个详细信息视图并将信息放在那里,因为其中会有很多行包含信息所以那是不可能的。现在这不是什么大问题,但我认为我没有做我应该做的事情。基本上我是这样传递信息的: 在“prepareforsegue”函数中,从tableview到detailview我使用“if indexPath.row == 0”,然后根据选择的行传递信息,我有一个整数变量,设置为在 tableview 上单击的行也被传递给 detailview,因此在 detailview 中我知道将哪个网站传递给 webview 或位置传递给 mapview,显然随着更多点被添加到我的 tableview,我必须添加更多“如果”,我只是不确定这是否是正确的方法,或者是否有更简单的方法来做到这一点。

【问题讨论】:

    标签: swift tableview hierarchical-data detailview pass-data


    【解决方案1】:

    您应该有一个类来封装与单个表行/详细视图相关的所有信息。我们就叫它model吧。

    在表格视图控制器中,您将有一个 models 数组,例如

    var models = [model]()
    

    您将覆盖 cellForRowAtIndexPath 以返回基于特定模型的单元格,例如

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("someCellId", forIndexPath: indexPath) as! UITableViewCell
    
        let model = models[indexPath.row]
    
        // Set the title of the cell to be the title of the logItem
        cell.textLabel?.text = model.name
        cell.detailTextLabel?.text = model.details
        return cell
    }
    

    在情节提要中转入细节视图,然后将整个model 传递给细节视图

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
        if (segue.identifier == "segueToDetail") {
            var svc = segue.destinationViewController as! DetailViewController
            svc.model = models[tableView.indexPathForSelectedRow()!.row]
        }
    }
    

    这样您只传递一个对象,而不必设置所有详细视图标签等。然后详细视图可以将同一对象传递到地图视图或其他视图。

    【讨论】:

    • 好的,我正在使用数据模型,现在,我如何在详细视图中接收它?我没有正确理解那部分
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    相关资源
    最近更新 更多