How to change the value of a label in ViewController using tableview by selecting a cell

enter image description here

Here is the class

import UIKit class CreateNoteViewController : UIViewController, UITextFieldDelegate, UITextViewDelegate { var tableData = ["One","Two","Three"] let labelSpecieText = "Specie" @IBOutlet weak var nameField: UITextField! @IBOutlet weak var labelSpecie: UILabel! required init (coder aDecoder:(NSCoder!)){ super.init(coder:aDecoder)! } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) labelSpecie.text = labelSpecieText } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{ let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"CellSpecie") cell.textLabel?.text = tableData[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let path = tableView.indexPathForSelectedRow let cell = tableView.cellForRowAtIndexPath(path!) labelSpecie.text = cell!.textLabel?.text } } 
  • 2
    why not just write labelSpecie.text = tableData[indexPath.row] ? - Max Mikheyenko

1 answer 1

UPD Check for more outlets :

enter image description here


Suppose that everything works correctly for you, the text simply does not change right away. Add:

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath)! as! UITableViewCell dispatch_async(dispatch_get_main_queue(), { self.labelSpecie.text = cell.textLabel!.text }) } 
  • But does it happen that didselectrowatindexpath is not called on main thread? - Max Mikheyenko
  • @MaxMikheyenko judging by the many topics, it happens, or it is because of something else. For example, stackoverflow.com/questions/20320591/… . Also, by the way, you need to find out, what about the delegate from UITableView - VAndrJ