首页 > 解决方案 > 如何从 UITextField 向 UITableView 添加多个数据?(斯威夫特 4)

问题描述

我正在尝试在 Xcode 上创建一个程序,该程序允许用户通过文本字段(单击按钮时)将多个数据输入到表格视图中。添加数据时,我希望在应用程序关闭后将其存储而不是删除 - 对于这一部分,我相信我必须使用 NSUserDefaults,但是,我不确定如何保存字符串数组?(我只熟悉存储单个字符串)。

这就是我的视图控制器当前的样子。

我根本没有在我的视图控制器上做太多事情,但这就是它目前所拥有的。

import UIKit

class NewViewController: UIViewController {

@IBOutlet weak var text: UITextField!

@IBOutlet weak var tableView: UITableView!



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.
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

标签: iosswiftxcodeuitableviewnsuserdefaults

解决方案


尝试以下操作:

  1. 创建一个数组,该数组将存储通过UITextField(即。var array = [String]()

  2. 在该add按钮的操作中,将用户在文本字段中输入的文本附加到数组中。

    if text.text != "" && !text.text.isEmpty {
         // append the text to your array 
         array.append(text.text!) 
         text.text = "" // empty the `UITextField`
    }
    
  3. 在您的tableView方法中,为您的自定义numberOfRows return array.count添加并添加一个,它将在单独的单元格中显示数组中的每个输入项。UILabelUITableViewCell


推荐阅读