我正在创建一个应用程序,在文本字段中写入一个字符串,然后将其保存在一个数组中。该数组显示在嵌入 mainViewController 中的 tableViewController 中。情况如下。 http://i.stack.imgur.com/z5uTc.png 。 我希望每次点击绿色的“保存”按钮时,我在 textField 中写入的字符串都会被保存并显示在 tableView 中,并且 textField 返回空,因此我可以重写一个字符串,将其添加到数组中。在本例中,tableView 显示了我在同一个文本字段中写入的两个字符串。我尝试为两个 viewController(mainViewVC 和 tableVC)编写代码。
主VC
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()
}
}
表VC
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
}
我写的代码不起作用。我可以在我的设备上编译并运行该应用程序,但是当我点击绿色的“保存”按钮时,该应用程序崩溃了。错误消息为“ fatal error :展开可选值时意外发现 nil”,位于“保存”IBAction 中的 embTableVC.myTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
行上。
你能帮助我吗?
非常感谢:)
最佳答案
仅当您转到下一个 ViewController 时,您才初始化 embTableVC,但您尝试在保存函数中访问它,而它仍然是 nil。
在访问它之前初始化它。
关于arrays - 来自文本的数组并显示在 tableView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35361802/