iosfan iosfan - 6 months ago 30
Swift Question

How can I pass string to textView using segue?

There is a

tableView
which has a
section
with title "Notes". Originally there is one
row
with
string
"Click here to add notes". After clicking the
cell
it
segues
to a
textView
and add notes. Now there is a new cell with note in the section ("Click here to add notes" is the second row now). When clicking the cell with note and segue to the textView again, I want the textView to show the
note
before editing and I pass the note by segue. But the error shows
fatal error: unexpectedly found nil while unwrapping an Optional value
. Please help to find out the problem.

My code:

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

switch indexPath.section {

case 0-3: break

case 4:

self.performSegueWithIdentifier("toTextView", sender: indexPath)

default: break
}

}


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

if segue.identifier == "toTextView" {

let indexPath = sender as! NSIndexPath

let noteText = detailsInSection[4][indexPath.row] as! String

let textVC = segue.destinationViewController as! TextViewController

if noteText == "Click here to add notes" {

// do nothing

} else {

textVC.notesTextView.text = noteText // Break point is here

}

}
}

Answer

As per comments, the notesTextView is nil, because the view in textVC has not been loaded at this point. Change your code to add a noteText property to TextViewController, set that value in prepareForSegue, and then in viewDidLoad of the TextViewController, set notesTextView.text = noteText.

Comments