如何从 UITextField 向 UITableView 添加多个数据? (SWIFT 4)

How to add multiple data to a UITableView from a UITextField? (SWIFT 4)

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

This is what my view controller currently looks like.

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

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

}

尝试以下操作:

  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 并为您的自定义 UITableViewCell 添加一个 UILabel在单独的单元格中显示数组中每个输入的项目。

如果您想在 table 视图中显示您的数据,您需要实施 table 视图委托。添加一个 table 带有标签的视图单元格

@IBOutlet weak var text: UITextField!

@IBOutlet weak var tableView: UITableView!

let NSUD_DATA = "dataarray_store"

var dataArray : NSMutableArray!
var userDefault = UserDefaults.standard


    override func viewDidLoad() {
        super.viewDidLoad()

        dataArray = NSMutableArray()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


//MARK:- create a button for adding the strings to array and while clicking that button

func onClickButton(){
    let string = text.text
    dataArray.add(string)
    userDefault.set(dataArray, forKey: NSUD_DATA)

}

用于获取存储在 userdefault 中的数组

func getData() -> NSMutableArray?{
    if userDefault.object(forKey: NSUD_DATA) != nil{
        return userDefault.array(forKey: NSUD_DATA) as! NSMutableArray
    }
    return nil
}

让我们逐步解决这个问题...

TL;DR - 为方便起见,我将最终代码放在 Github 上的 sample project 中。随意使用您的应用程序中的任何或所有代码。祝你好运!

第 1 步 - 遵守 UITableView 协议

"...enter multiple data into a table view..."

UITableView 至少需要您遵守两个协议才能显示数据:UITableViewDelegateUITableViewDataSource。如果您使用内置的 UITableViewController 对象,Interface Builder 会为您处理协议声明,但在您的情况下,您不能使用该对象,因为您只希望 UITableView 占据视图的一部分。因此,您必须通过将它们添加到 ViewController 的签名来自己实现协议:

Swift 4

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

}

步骤 2 - 实现 UITableView 协议所需的方法

现在您已经声明了协议,Xcode 会显示一个错误,直到在您的 ViewController class 中实现了三个必需的方法.这些方法的最低限度实现是:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return UITableViewCell()
}

稍后您将实现这些方法,但此时您的代码应该可以编译。

步骤 3 - 将 UITableView 的协议连接到 ViewController

由于您使用的是标准 UITableView 对象,ViewController 默认情况下未连接到您刚刚在协议方法中实现的代码。要建立连接,请将这些行添加到 viewDidLoad():

override func viewDidLoad() {
    super.viewDidLoad()
    
    tableView.delegate = self
    tableView.dataSource = self
}

或者,您可以使用 Interface Builder 中的 CONTROL + DRAG 技术将委托和数据源从您的 UITableView 连接到 ViewController。

注意: 在这种情况下,self 指的是 ViewController 因为你在 ViewController class.

第 4 步 - UITextField 设置

"...through a text field..."

您之前为连接到 Interface Builder 的 UITextField 添加了一个 IBOutlet,因此这里没有什么可做的了。

第 5 步 - 添加按钮的 IBAction

(when a button is clicked)."

您需要将 IBAction 添加到 ViewController class 并将其连接到 Interface Builder 中的添加按钮。如果您更喜欢编写代码然后连接操作,请将此方法添加到您的 ViewController:

@IBAction func addButtonPressed(_ sender: UIButton) {

}

如果您使用 Interface Builder 和 CONTROL + DRAG 技术连接动作,该方法将自动添加。

步骤 6 - 添加数组 属性 来存储数据条目

"...save an array of strings..."

您需要一个字符串数组来存储用户的条目。添加一个 属性 到初始化为空字符串数组的 ViewController:

var dataArray = [String]()

第 7 步 - 完成 UITableView 协议方法的实现

至此,您已拥有完成实现 UITableView 协议方法所需的一切。将代码更改为以下内容:

//1
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //Do nothing   
}

//2
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dataArray.count
}

//3
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.textLabel?.text = dataArray[indexPath.row]
    return cell
}
  1. 将来,如果您想在用户点击单元格时执行某些操作,您将需要将代码添加到 tableView(_:didSelectRowAt:)

  2. 您现在创建的行数与 dataArray 中的值数相同。

  3. 要使其与 Interface Builder 一起使用,请确保转到 UITableViewCell 的属性检查器并将 Cell Identifier 设置为 单元格。查看文档以获取有关 Dequeuing Cells.

    的更多信息

第 8 步 - 完成 addButtonPressed(_:) 的实现

中所建议,您需要在操作中实现将用户文本附加到数组的代码,但前提是文本不为空白或为空。检查 dataArray 是否已包含您使用 dataArray.contains 输入的值也是一个好主意,具体取决于您要完成的任务:

if textField.text != "" && textField.text != nil {
    let entry = textField.text!
    if !dataArray.contains(entry) {
        dataArray.append(entry)
        textField.text = ""
    }
    tableView.reloadData()
}

步骤 9 - 使用 UserDefaults 保存数据

"When the data is added I would like it to be stored and not be deleted after the app is closed."

要将 dataArray 保存到 UserDefaults,请在 addButtonPressed(_:) 操作中附加条目的行之后添加这行代码:

UserDefaults.standard.set(dataArray, forKey: "DataArray")

要从 UserDefaults 加载 dataArray,请在调用 super:

后将这些代码行添加到 viewDidLoad()
if let data = UserDefaults.standard.value(forKey: "DataArray") as? [String] {
    dataArray = data
}