Search code examples
stringswifttextviewuitextviewiboutlet

Displaying input text on different views


Was wondering if anybody could help on a simple problem

I have a UITextView on one page, where I want to enter text and store it in a string. Then when the next page is accessed, I would like that text to be displayed on that page, either in a new UITextView or some other way.

In my PostViewController.swift file (the first page) to get the input string, I have

@IBOutlet weak var postTextView: UITextView!

I tried making a new UITextView on the other view controller to try and display the string, and had the subsequent code, but can't figure it out from here.

@IBOutlet weak var copyText: UITextView!

let text: NSString = PostViewController().postTextView.text
???copyText = text??? (not sure if this is even close to right)

Any ideas would be appreciated and apologies for the noob question


Solution

  • In your PostViewController, implement prepareForSegue() to assign the value of its textfield to the variable in the second controller.

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    
            if segue.identifier == "showSecondVC" { // Make sure the segue has this identity in Interface Builder
    
                let vc = segue.destinationViewController as! SecondVC // Change that to the actual class name
    
                vc.textFromVC1 = postTextView.text
            }
        }
    

    In your second ViewController:

    class SecondviewController: UIViewController {
    
        var textFromVC1: String!
    
        @IBOutlet weak var myTextField: UITextField!
    
        override func viewDidLoad() {
            myTextField.text = textFromVC1
        }
    }