Tom Wicks Tom Wicks - 2 years ago 113
Swift Question

Delegate method to pass data forward

I am successfully passing data back between two view controllers using a delegate method.

The first view controller is a "Review" screen and the second is an "Edit" screen which mainly contains a UITextView.

When I change the content of the Text View on the edit screen and hit save it successfully passes to the review screen. However when I return to the Edit screen the UITextView is empty.

How can I make sure the edit screen keeps the value that is stored in the delegate?

Thanks for taking the time to have a look.

Review View Controller

class AddCampaignViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate, TitleViewDelegate {

@IBOutlet var titleSubtitle: UILabel!

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

if segue.identifier == "AddTitleViewController" {

let addTitleViewController = segue.destinationViewController as! AddTitleViewController

addTitleViewController.delegate = self



override func viewDidLoad() {



func setCampaignTitle(campaignTitle: String) {

titleSubtitle.text = campaignTitle



Edit View Controller

protocol TitleViewDelegate {

func setCampaignTitle(campaignTitle: String)


class AddTitleViewController: UIViewController, UITextViewDelegate {

var delegate : TitleViewDelegate!

var campaignTitle : String!

@IBOutlet var titleTextView: UITextView!

override func viewDidLoad() {



let logButton : UIBarButtonItem = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.Plain, target: self, action: "saveTitle:")

self.navigationItem.rightBarButtonItem = logButton


func saveTitle(sender: UIBarButtonItem) {





Answer Source

The segue will create a new EditViewController every time. To pass data forward, you will need to assign the data to an EditViewController property and then copy that data into titleTextView.text in the viewDidLoad method. This is necessary because the @IBOutlets are not set up and are still nil when prepareForSegue runs.


  1. add the property var textToEdit = "" to your EditViewController.
  2. In prepareForSegue, set addTitleViewController.textToEdit = /* the text you want to edit */
  3. In viewDidLoad of EditViewController, set titleTextView.text = textToEdit.

Note: Your delegate should be declared weak to avoid a retain cycle (which will cause you to leak memory by never freeing EditViewControllers. Your @IBOutlets should also be declared weak.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download