在层次结构中传递数据的最佳方法是什么?迅速

时间:2015-08-17 06:01:03

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

所以我正在开发一个应用程序,它有几个表格视图,可以带您进入详细视图,详细视图可以带您到mapview或webview,这是我的意思的一个例子: enter image description here

我没有制作几个细节组(细节,网页,地图),而是制作所有的桌面视图,带你到相同的detailView并将信息放在那里,因为会有很多行包含信息,所以这是不可能的。现在问题不在于现在,但我认为我并没有按照自己的意愿做事。基本上我这样传递信息: 在“prepareforsegue”函数中,从tableview到detailview,我使用“if indexPath.row == 0”,然后只根据所选行传递信息,我有一个整数变量,设置为数量在tableview上点击的行,也被传递给detailview,因此在detailview中我知道要将哪个网站传递到webview或mapview的位置,显然当我的tableview中添加了更多的点时,我必须添加更多“如果”,我只是不确定这是否是正确的方法,或者是否有更简单的方法来做到这一点。

1 个答案:

答案 0 :(得分:1)

您应该有一个类,它封装了与单个表行/详细信息视图相关的所有信息。我们称之为model

在表视图控制器中,您将拥有一个model s数组,例如

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
}

在故事板中为细节视图制作一个segue,然后将整个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]
    }
}

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

相关问题