Andrew DR
Andrew DR

Reputation: 47

Trying to Pass a selected tableview cell value to a NavigationBar Title in swift

Excuse the Newbie question I have been trying everything but haven't been able to get this to work :(

I have a list in a tableview and ideally when a cell (row) is selected it displays the selected cell text as the Title for a Navigation Bar.

Here is the call for what I have thought should pass the selected value to the next segue

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
    let selectedTopic = Topics[indexPath.row]
    
    let Sentences = SentencesVC()
    Sentences.TopicPassed = selectedTopic.heading
    
    self.performSegueWithIdentifier("gotoSentences", sender: tableView)
    let pathSelect = TopicTableView.indexPathForSelectedRow()
    pathSelect
}

And the code for the other ViewController:

var TopicPassed:String!

@IBOutlet weak var NavBar: UINavigationBar!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    self.navigationItem.title = TopicPassed
    
}

Any help would be greatly appreciated as it is driving me nuts and I am not sure how many times I have tried different solutions to no avail.

Thanks in advance

Upvotes: 2

Views: 1261

Answers (2)

Romain
Romain

Reputation: 3758

As you are using storyboards and segues, add this function to your view controller's code:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if segue.identifier == "gotoSentences" {
        let selectedTopic = Topics[tableView.indexPathForSelectedRow().row]
        let sentences = segue.destinationViewController as SentencesVC
        sentences.TopicPassed = selectedTopic.heading
    }
}

As a side note, in your naming schemes, be careful and try not to use capitalized vars in your code. Swift uses a "camelCase" convention, and capitalized words are usually reserved to type names (classes, etc.). For clarity, you could rename Topics to topics, TopicPassed to topicPassed, etc.

Upvotes: 1

Dejan Skledar
Dejan Skledar

Reputation: 11435

Change your segue like this:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if (segue.identifier == "gotoSentences") {
        var otherView = segue.destinationViewController as OtherViewController;

        var index = mainTableView.indexPathForSelectedRow()

        otherView.title = Topics[index.row]
    }

}

Upvotes: 0

Related Questions