Passing text from text file to UITextView in "Swift 3"
This is probably the simplest way of doing it.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBAction func readFile1(_ sender: Any) {
self.textView.text = load(file: "file1")
}
@IBAction func readFile2(_ sender: Any) {
self.textView.text = load(file: "file2")
}
@IBAction func readFile3(_ sender: Any) {
self.textView.text = load(file: "file3")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.textView.text = load(file: "file1")
}
func load(file name:String) -> String {
if let path = Bundle.main.path(forResource: name, ofType: "txt") {
if let contents = try? String(contentsOfFile: path) {
return contents
} else {
print("Error! - This file doesn't contain any text.")
}
} else {
print("Error! - This file doesn't exist.")
}
return ""
}
}