bzimm01 bzimm01 - 22 days ago 6
Swift Question

swift - How to correctly set up a UITextView

I have a view controller that only has a UITextView in it. I'm having a problem initializing the UITextView with another one that I pass to the view controller.

Here's the code for the view controller:

(The File class has a string variable: name, and UITextView variable: content)

// MARK: Properties
var file: File?
@IBOutlet weak var textViewHome: UITextView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

navigationItem.title = file?.name
self.automaticallyAdjustsScrollViewInsets = false

print(file?.content.text)
print(textViewHome.text)
textViewHome = file?.content
print(textViewHome.text)
}


The output of those print statements are:

Optional("hello")

hello


So the textViewHome variable gets set with the correct string but nothing shows up in text view when the app is run. I've seen a lot of questions similar to this but haven't found one where the UITextView.text variable is correct but nothing actually shows up. Thanks for any advice

Answer

The main problem is that your view hierarchy (what's is showing on the screen) had textViewHome because it's a subview of viewController.view. When you changed the pointer of textViewHome, the view hierarchy still had the old one because you changes the viewController's pointer and you didn't touch the hierarchy.

Design Improvement: It's better to let the File own a string and not UITextView.

class File{
    var name: String
    var content: String
}

In your viewController, you will have

textViewHome.text = file?.content //content is a string
Comments