ios - 如何在 Swift 中将数据从一个 TableView 传递到另一个 TableView ?

标签 ios uitableview swift uinavigationcontroller

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)!")

    }               
}

最佳答案

您可以显式构建新的 View Controller ,并在检测到一行被选中时传入数据:

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? = ""
}

关于ios - 如何在 Swift 中将数据从一个 TableView 传递到另一个 TableView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24177461/

相关文章:

ios - 键盘换页导致输入问题

ios - 如何加快AppCode自动完成速度?

ios - 在 Swift iOS9 中从 Json 数据中提取值

ios - 在部分中展开/折叠 UITableView 行的问题

ios - 使用 AVPlayerViewController 从 HTTP 实时流中获取视频详细信息

ios - phonegap Inappbrowser 不显示位置栏(ios)

ios - iOS 上的 Facebook SDK 4.6 登录按钮不使用 Facebook 应用程序进行身份验证

ios - 在单元测试中手动向左滑动以调用处理程序以在 Swift 中进行测试

ios - 会在 Swift 构建内存中一遍又一遍地声明相同的 var 吗?

ios - preferredMaxLayoutWidth 在 Swift 中不起作用?