Sam*_*adi 6 text-files ios swift
我是iOS开发的初学者,我正在尝试创建一个简单的应用程序,它将文本从文本文件传递到"Swift 3"中的UITextView.我在YouTube,堆栈和其他网站上查找过很多教程,但是所有这些教程似乎都给了我很多错误,或者对我来说太难理解了(因为我太没经验了).
有三个按钮,三个文本文件和一个文本视图.当用户单击第一个按钮时,file1将被加载到文本字段中.
我的一些尝试,它在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()
}
}
Run Code Online (Sandbox Code Playgroud)
Tri*_*ton 10
这可能是最简单的方法.
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 ""
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2015 次 |
| 最近记录: |