我正在创建一个应用程序,它在一个文本字段中写入一个字符串,并将其保存在一个数组中。该数组显示在嵌入mainViewController中的tableViewController中。情况如下。 http://i.stack.imgur.com/z5uTc.png。 我希望每次点击绿色的“保存”按钮时,我在textField中写入的字符串被保存并显示在tableView中,并且textField返回空白,因此我可以重新编写一个字符串,该字符串添加到数组中。在这种情况下,tableView显示了两个字符串,我写在同一个textField中。我试图编写两个viewControllers(mainViewVC和tableVC)的代码。从文本中的数组和显示在表中查看
MainVC
import UIKit
class mainVC: UIViewController {
@IBOutlet var txtField: UITextField!
var embTableVC: tableVC!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "embededTableVC" {
embTableVC = segue.destinationViewController as! tableVC
}
}
@IBAction func Save() {
if let Text = txtField.text {
if txtField.text == "" {
myArray.append(Text)
let row = myArray.count-1
let indexPath = NSIndexPath(forRow: row, inSection: 0)
embTableVC.myTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
txtField.text = ""
txtField.resignFirstResponder()
}
}
TableVC
import UIKit
var myArray = [String]()
class tableVC: UITableViewController {
@IBOutlet var myTableView: UITableView! {
didSet {
myTableView.dataSource = self
myTableView.delegate = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
myTableView.dataSource = self
myTableView.delegate = self
myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "customcell")
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
myTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCellWithIdentifier("customcell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = myArray[indexPath.item]
return cell
}
我写不工作的代码。我可以编译和运行我的设备上的应用程序,但是当我点击绿色的“保存”按钮时,应用程序崩溃。在“保存”IBAction中,错误消息是“致命错误:在解包可选值时意外发现零”:embTableVC.myTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
。 你能帮我吗? 非常感谢:)
在课前,你的意思是? –
您尝试更新尚不存在的内容。 而不是var embTableVC:tableVC! ,写如var embTableVC = embTableVC() (但也许它会更好,如果你将“保存功能”移动到embTableVC类 – Roee84