Swift: 将 UITableViewCell 标签传递给新 ViewController

Swift: Pass UITableViewCell label to new 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) 
}

你问过:

How do I get the label of the cell when it is selected and then also pass that to another ViewController?

我可能建议将问题改写如下:"How do I retrieve the data associated with the selected cell and pass it along to another view controller?"

这听起来可能是一回事,但这里有一个重要的概念区别。您真的不想从单元格标签中检索值。我们的应用程序采用 MVC 范式,因此当您想要将数据信息从一个场景传递到另一个场景时,您想要返回到模型(items 数组),而不是视图(text 属性 的 UILabel).

这是一个微不足道的例子,所以这种区别有点学术性,但随着应用程序变得越来越复杂,这种回归模型的模式变得越来越重要。单元格中的字符串表示通常不能很好地替代实际模型对象。而且,正如您将在下面看到的,从模型中检索数据同样容易(如果不是更容易的话),所以您应该这样做。

顺便说一句,在这种情况下您根本不需要 didSelectRowAtIndexPath 方法。您所需要的只是从 table 视图单元格到目标场景的转场,为该转场赋予一个唯一标识符(在我的示例中为 Details),然后实现 prepare(for:sender:):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? DetailsViewController {
        let selectedRow = tableView.indexPathForSelectedRow!.row
        destination.selectedValue = items[selectedRow]
    }
}

或者,如果您的 segue 位于单元格和目标场景之间,您还可以使用 prepare(for:sender:):

sender
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? DetailsViewController {
        let cell = sender as! UITableViewCell
        let selectedRow = tableView.indexPath(for: cell)!.row
        destination.selectedValue = items[selectedRow]
    }
}

但思路是一样的。确定选择了哪一行,并从模型 items 数组中检索信息。

以上是Swift3.Swift2.3请看本回答previous version

好的..已经 2 天了,我一直在寻找如何保存 selected UITableViewCell 标签文本数据并显示的答案数据到另一个视图控制器上的另一个标签,该标签将在点击一个单元格后出现。最后我完成了任务并且成功了。这是完整的代码,其中包含使用 Swift.I 和 Xcode 6.4.

的步骤

第 1 步

我有两个 class 分配给名为 "iOSTableViewControllerClass.swift" 的故事板视图控制器,它是一个 Table 视图控制器和 "iOSTutorialsViewControllerClass.swift" 这是一个普通的视图控制器。

第 2 步

现在通过在故事板区域按住 Control 键拖动并选择 "show" 从下拉菜单中。根据下图单击此突出显示的按钮并执行 segue。

第 3 步

现在 select 通过单击情节提要并在 Attributes Inspector 上给它一个标识符来进行 segue。在这种情况下,我将其命名为 "iOSTutorials"

第 4 步

现在,在这一步中,在您的单元格和其他视图控制器上放置一个标签,并在它们相应的 classes 上制作它们的出口。 在我的例子中,这些是“@IBOutlet weak var iOSCellLbl: UILabel!”和“@IBOutlet weak var iOSTutsClassLbl: UILabel!”。

第 5 步

在第一个 Table View Controller Class 上创建一个字符串类型变量。我这样做是因为 "var sendSelectedData = NSString()" 还在第二个 class 上创建了一个字符串类型变量。我这样做是因为 "var SecondArray:String!".

第 6 步

现在我们准备好了。 这是第一个 Class --

的完整代码
 // iOSTableViewControllerClass.swift

  import UIKit

  class iOSTableViewControllerClass: UITableViewController, UITableViewDataSource,UITableViewDelegate {

  // Creating A variable to save the text from the selected label and send it to the next view controller

  var sendSelectedData = NSString()

 //This is the outlet of the label but in my case I am using a fully customized cell so it is actually declared on a different class
@IBOutlet weak var iOSCellLbl: UILabel!

//Array for data to display on the Table View
var iOSTableData = ["Label", "Button", "Text Field", "Slider", "Switch"];
override func viewDidLoad() {
    super.viewDidLoad()

//Setting the delegate and datasource of the table view

    tableView.delegate = self
    tableView.dataSource = self

//Registering the class here
    tableView.registerClass(CustomTableViewCellClassiOS.self, forCellReuseIdentifier: "CellIDiOS")

//If your using a custom designed Cell then use this commented line to register the nib.
    //tableView.registerNib(UINib(nibName: "CellForiOS", bundle: nil), forCellReuseIdentifier: "CellIDiOS")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the number of rows in the section.
    return iOSTableData.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let CellIDentifier = "CellIDiOS"

 //In this case I have custom designed cells so here "CustomTableViewCellClassiOS" is the class name of the cell
    var cell:CustomTableViewCellClassiOS! = tableView.dequeueReusableCellWithIdentifier(CellIDentifier, forIndexPath: indexPath) as? CustomTableViewCellClassiOS
    if cell == nil{
        tableView.registerNib(UINib(nibName: "CellForiOS", bundle: nil), forCellReuseIdentifier: CellIDentifier)
        cell = tableView.dequeueReusableCellWithIdentifier(CellIDentifier) as? CustomTableViewCellClassiOS

    }
 //Here we are displaying the data to the cell label
    cell.iOSCellLbl?.text = iOSTableData[indexPath.row]
    return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    println("You selected cell #\(indexPath.row)!")

    // Get Cell Label text here and storing it to the variable
    let indexPathVal: NSIndexPath = tableView.indexPathForSelectedRow()!
    println("\(indexPathVal)")
    let currentCell = tableView.cellForRowAtIndexPath(indexPathVal) as! CustomTableViewCellClassiOS!;
    println("\(currentCell)")
    println("\(currentCell.iOSCellLbl?.text!)")
    //Storing the data to a string from the selected cell
    sendSelectedData = currentCell.iOSCellLbl.text!
    println(sendSelectedData)
//Now here I am performing the segue action after cell selection to the other view controller by using the segue Identifier Name
    self.performSegueWithIdentifier("iOSTutorials", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

//Here i am checking the Segue and Saving the data to an array on the next view Controller also sending it to the next view COntroller
    if segue.identifier == "iOSTutorials"{
//Creating an object of the second View controller
        let controller = segue.destinationViewController as! iOSTutorialsViewControllerClass
//Sending the data here
        controller.SecondArray = sendSelectedData as! String

 }

这是第二个的完整代码Class..--

//  iOSTutorialsViewControllerClass.swift

import UIKit

class iOSTutorialsViewControllerClass: UIViewController {

//Creating the Outlet for the Second Label on the Second View Controller Class
@IBOutlet weak var iOSTutsClassLbl: UILabel!

//Creating an array which will get the value from the first Table View Controller Class
var SecondArray:String!

override func viewDidLoad() {
    super.viewDidLoad()

//Simply giving the value of the array to the newly created label's text on the second view controller
   iOSTutsClassLbl.text = SecondArray
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

我是这样做的

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

 let selectedName = nameArray[indexPath.row]      

let newView: nextViewName = self.storyboard?.instantiateViewController(withIdentifier: "nextViewName") as! nextViewName

   newView.label.text = selectedValue
   self.present(newView, animated: true, completion: nil)



}