I'm a beginner in iOS development and I am trying to make a simple app which Passing text from text file to UITextView in "Swift 3". I have looked up many tutorials on YouTube, stack and other websites, but all of them seem to either give me a lot of errors or are too hard for me too understand (as I am too unexperienced).
There are three buttons, and three text files, and one text view. When user clicks on the first button, file1 will be loaded into the text field.
Some of my attempts, it's give me error on txt_view.text = txt1.txt
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var txt_view: UITextView!
@IBAction func btn_txt1(_ sender: Any) {
txt_view.text = txt1.txt
}
@IBAction func btn_txt2(_ sender: Any) {
txt_view.text = txt2.txt
}
@IBAction func btn_txt3(_ sender: Any) {
txt_view.text = txt3.txt
}
override func viewDidLoad(){
super.viewDidLoad()
}
override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
}
}
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 ""
}
}
Following is the way to load the text file in the text view.
Swift 4.x
func loadFileContent(_ fileName: String) {
if let path = Bundle.main.path(forResource: fileName,
ofType: "txt") {
do {
let text = try String(contentsOfFile: path, encoding: .ascii)
openSourceTextView.text = text
} catch let error {
debugPrint(" Error - \(error.localizedDescription)")
}
}
NOTE:
If skip the encoding or using the encoding: .utf8 you will get the following errors -
The file “fileName.txt” couldn’t be opened because the text encoding of its contents can’t be determined.
OR
The file “fileName.txt” couldn’t be opened using text encoding Unicode (UTF-8).
so used encoding: .ascii
while loading content of the text file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With