ios - 如何从 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.
}
*/
}
解决方案
尝试以下操作:
创建一个数组,该数组将存储通过
UITextField
(即。var array = [String]()
在该
add
按钮的操作中,将用户在文本字段中输入的文本附加到数组中。if text.text != "" && !text.text.isEmpty { // append the text to your array array.append(text.text!) text.text = "" // empty the `UITextField` }
在您的
tableView
方法中,为您的自定义numberOfRows
return array.count
添加并添加一个,它将在单独的单元格中显示数组中的每个输入项。UILabel
UITableViewCell
推荐阅读
- scheme - 建立一个具有相同 n 项的列表
- ios - 切换方案后 Xcode 配置不会改变
- firebase - 如何在离线模式下更新 Firebase 实时数据库“推送”上的 UI
- python - 在 Django 中使用 JSONField 进行批量更新
- python - pandas_datareader._utils.RemoteDataError:无法读取 URL:https://finance.yahoo.com/quote/CBOE
- linux - 在詹金斯管道中用 envsubst 替换文件变量
- angular - 具有多个嵌套组件的 Angular 2-way 绑定
- javascript - 如何同时验证多个输入字段
- c# - 如何使autofac实时解析带参数的构造函数?
- android - 添加带有导航抽屉的启动屏幕活动不起作用