【发布时间】:2019-11-24 08:18:46
【问题描述】:
我正在使用 Swift 在 Xcode 中为 iPhone 制作应用程序,我在 Main.Storyboard 上添加了多个按钮,并且每个按钮都有一个 txt 文件,例如
class ViewController: UIViewController {
@IBAction func Button1(_ sender: Any) {
opneTextFile(fileName: "example")
}
@IBAction func Button2(_ sender: Any) {
opneTextFile(fileName: "example1")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func opneTextFile(fileName : String) {
if let filepath = Bundle.main.path(forResource: fileName, ofType: "txt") {
do {
let contents = try String(contentsOfFile: filepath)
print(contents)
// Now push second ViewController form here with contents.
if let secondVC = self.storyboard?.instantiateViewController(withIdentifier: "TextViewVC") as? TextViewVC {
secondVC.content = contents
self.navigationController?.pushViewController(secondVC, animated: true)
}
} catch {
// contents could not be loaded
}
} else {
// example.txt not found!
}
}
这是我的 TextViewVC,我在 Storyboard 中使用 TextView 创建了一个新的 ViewController 并将其与 TextViewVC 文件链接
class TextViewVC: UIViewController {
@IBOutlet var textView: UITextView!
var content : String?
override func viewDidLoad() {
super.viewDidLoad()
textView.text = content
// Do any additional setup after loading the view.
}
错误
但我不知道如何在用户单击按钮时打开文件,它应该类似于当用户单击按钮 1 时,txt1 文件应该在 ViewController2 中打开,当用户单击按钮 2 时,txt2 文件应该在相同时打开用户单击 button1 txt1 文件应在 ViewController 中以 Button1 的形式打开,其余按钮也是如此。
【问题讨论】:
标签: ios swift xcode viewcontroller