I have a tableview with cell data. When I click the cell, it takes me to another view controller and displays the cell label in a UIlabel on the new ViewController.
However, When I go back to the tableview and select a different cell, the value on the new view controller doesn't update immediately. It displays the last clicked cell, then if I go back and repeat the process a second time it will update.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let currentCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
self.labeltosend = currentCell.textLabel!.text!
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == PostSegueIdentifier {
if let destination = segue.destinationViewController as? NewViewController {
destination.newlabel = labeltosend
}
}
}
Am I supposed to reload the data somehow?
@IBOutlet weak var dispLabel: UILabel!
var newlabel = String()
override func viewWillAppear(animated: Bool) {
dispLabel.text = newlabel
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
prepareForSegue(_:sender)
is not called if you draw segue
from cell to next view controller. Try to draw segue from view controller to view controller. And perform a manual segue using performSegueWithIdentifier("MySegueIdentifier" sender:self)
in tableView(_:didSelectRowAtIndexPath:indexPath)
. For more info please have a look at this answer .
Think prepareForSegue is sometimes getting called before didSelectRowAtIndexPath you can move that code to prepareForSegue. When you set up a segue as you have sender in prepareForSegue is the indexPath of row tap, precisely so you can do these sorts of things.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == PostSegueIdentifier {
if let destination = segue.destinationViewController as? NewViewController {
let indexPath = sender as NSIndexPath
let currentCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
self.labeltosend = currentCell.textLabel!.text!
destination.newlabel = labeltosend
}
}
}
You should read Duncan's comment.
First: if you have your segue connected from the UITableViewCell, don't. Delete it and connect the segue from the view controller itself.
Second: on the didSelectRowAtIndexPath
method, call prepareForSegue
method.
And finally on the destination controller:
@IBOutlet weak var dispLabel: UILabel!
var newlabel = String()
override func viewWillAppear(animated: Bool) {
//dispLabel.text = newlabel
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
dispLabel.text = newlabel
}
Also, you need to improve your naming convention. Is really confusing
Hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.