Swift:将UITableViewCell标签传递给新的ViewController

我有一个UITableView,它使用基于JSON调用的数据填充单元格。像这样:
var items = ["Loading..."]
var indexValue = 0

// Here is SwiftyJSON code //

for (index,item) in enumerate(json) {
    var indvItem = json[index]["Brand"]["Name"].stringValue
    self.items.insert(indvItem,atIndex: indexValue)
    indexValue++
}
self.tableView.reloadData()

选择单元格后,如何获取标签,然后将其传递给另一个ViewController?

我设法得到:

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

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    println(currentCell.textLabel.text)
}

我只是不知道如何将它作为一个变量传递给下一个UIViewController。

谢谢

在两个视图控制器之间传递数据取决于视图控制器如何相互链接。如果它们与segue链接,则需要使用performSegueWithIdentifier方法并覆盖prepareForSegue方法
var valuetoPass:String!

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

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    valuetoPass = currentCell.textLabel.text
    performSegueWithIdentifier("yourSegueIdentifer",sender: self)

}

override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject?) {

    if (segue.identifier == "yourSegueIdentifer") {

        // initialize new view controller and cast it as your view controller
        var viewController = segue.destinationViewController as AnotherViewController
        // your new view controller should have property that will store passed value
        viewController.passedValue = valuetoPass
    }

}

如果您的视图控制器没有与segue链接,那么您可以直接从tableView函数传递值

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

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
    let storyboard = UIStoryboard(name: "YourStoryBoardFileName",bundle: nil)
    var viewController = storyboard.instantiateViewControllerWithIdentifier("viewControllerIdentifer") as AnotherViewController
    viewController.passedValue = currentCell.textLabel.text
    self.presentViewController(viewContoller,animated: true,completion: nil) 
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...