【问题标题】:How to pass data from one table view to another table view in Swift?如何在 Swift 中将数据从一个表视图传递到另一个表视图?
【发布时间】:2014-06-12 06:05:45
【问题描述】:
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView: UITableView
    var dict1:Dictionary<Int,String> = [ 0:"One",1:"TwO",2:"Three"];

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }


    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return self.dict1.count;
    }

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

        cell.textLabel.text = self.dict1[indexPath.row]

        return cell
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("You selected cell #\(indexPath.row)!")

    }               
}

【问题讨论】:

  • 您需要将 selectedIndex 值传递给其他 ViewController 吗?

标签: ios uitableview swift uinavigationcontroller


【解决方案1】:

您可以显式构建新的视图控制器,并在检测到选择了一行时将数据传入:

override func tableView(tableView: UITableView!, didSelectRowAtIndexPath path: NSIndexPath!) {
    let entry = news[path.row] as NSDictionary
    let url = entry["link"] as NSString
    let secondViewController = 
        self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController")
        as SecondViewController

    // pass the relevant data to the new sub-ViewController
    secondViewController.url=url;
    // tell the new controller to present itself
    self.navigationController.pushViewController(secondViewController, animated: true)
}

并在 SecondViewController.swift 中添加一个变量来保存相关数据。

class SecondViewController: UIViewController {
    var url: String? = ""
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2022-11-29
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    相关资源
    最近更新 更多