2016-03-19 16 views
0

私の目標は、セル内でtextLabelを取り込んで新しいViewControllers UILabelで印刷するときです。TableViewのセルテキストを新しいviewControllerに印刷するUILabel(swift)

セルが選択されたときに、新しいView Controllerにプッシュされた場所に既に設定されています。私はちょうどそれを新しいViewControllerのUILabelにセルtextLabelを印刷する方法を理解できません。

ここに私のコードは、TableViewのですが、私の新しいViewControllerにセルのtextLabelを取得するために何を書く必要がありますか?

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

    tableView.deselectRowAtIndexPath(indexPath, animated: true) 

    let currentCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell 

    let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("showPostContent") as! showPostContent 

    print(currentCell.textLabel?.text) 

    self.navigationController?.pushViewController(secondViewController, animated: true) 

} 
+0

"secondViewController.FooBar =" some string ""を試してください。ここで、Foobarは、2番目のViewControllerで宣言した文字列です。 –

答えて

2

これまでのところ、私はあなたの質問では、コントローラから別のコントローラにデータを渡そうとしていることがわかりました。あなたのケースでは、セルがタップされたときにdidSelectRowAtIndexPathメソッドを使用し、secondViewControllerUILabelに値を設定するか、セルの次のコントローラにプッシュセグを設定して、prepareForSegueのデータを渡します必要。

ケース1:

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

    let currentCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell 
    let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("showPostContent") as! showPostContent 
    // this line call the loadView method to avoid the IBOutlet is not nil 
    let _ = secondViewController.view 

    // pass the data 
    secondViewController.NameOfYourUILabelOutlet.text = currentCell.textLabel?.text 

    print(currentCell.textLabel?.text) 
    self.navigationController?.pushViewController(secondViewController, animated: true) 
} 

ケース2:

あなたのストーリーボードにセグエを設定した後:

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

    let destinationViewController = segue.destinationViewController as! NameOfYourViewController 
    let _ = destinationViewController.view 

    guard let indexPath = self.tableView.indexPathForSelectedRow else { return } 

    let indexOfCellSelected = indexPath.row 
    let cell = self.tableView.cellForRowAtIndexPath(indexPath) 

    destinationViewController.NameOfYourUILabelOutlet.text = cell.NameOfYourUILabelOutlet.text 
} 

@IBOuletをインスタンス化するためにviewプロパティを呼び出さない場合は、プロパティを作成して値を設定し、次にviewDidLoadの中に@IBOuletの値を設定します。

私はこれがあなたに役立つことを願っています。

関連する問題