向 TableView 添加内容 Swift IOS
Adding content to a TableView Swift IOS
我该怎么做才能让用户将名字和姓氏输入到两个单独的文本字段中,然后使用该用户的输入将新单元格添加到 TableView 中(输入位于与table)
我还想知道如何存储从文本字段中获取的数据以保存在设备上并能够被用户删除。
用于制作table的代码:
var finalFirstName = String() // First Name from TextField
var finalLastName = String() // Last Name from TextField
var nameArry = ["Temp User", "Temp User2"] // Array of names used in creating table
这是将上述变量添加到 table:
的代码
func createArray() -> [Contacts] {
var tempContact1: [Contacts] = []
if (nameArry.count > 1) {
let contacts = Contacts(MyContact: userName, Me: "Me") // Add the users contact [default is user]
let contacts1 = Contacts(MyContact: nameArry[0], Me: "") // Add First item from nameArry
let contacts2 = Contacts(MyContact: nameArry[1], Me: "") // Add Second item from nameArry
tempContact1.append(contacts)
tempContact1.append(contacts1)
tempContact1.append(contacts2)
return tempContact1
}
else {
let contacts = Contacts(MyContact: userName, Me: "Me")
tempContact1.append(contacts)
return tempContact1
}
}
如有任何帮助,我们将不胜感激。
请注意,该项目已经创建,我不确定我是否有该项目的数据代码。
首先,您在createArray 方法中的逻辑并不理想。您应该循环遍历 nameArry 以动态生成 [Contacts] 数组。你可以简单地做这样的事情:
var finalFirstName = "" // First Name from TextField
var finalLastName = "" // Last Name from TextField
var nameArry = ["Temp User", "Temp User2"]
func createArray() -> [Contacts] {
var tempContact1: [Contacts] = []
tempContact1.append(Contacts(MyContact: userName, Me: "Me"))
for name in nameArry {
tempContact1.append(Contacts(MyContact: name, Me: ""))
}
}
针对你的问题。您需要在 UI 中添加某种完成按钮。如果用户单击它,将新名称添加到您的 nameArry 中,调用 createArray 更新您的 [Contacts] 数组,最后调用 tableview 的 reloadData() 以重新加载数据。您甚至可以通过将 nameArry 设为 Contacts 数组而不是 String 来改进此过程。这样,您将不需要任何映射方法 createArray.
最后,为了保存数据,理想情况下您需要使用Realm 或SQLite 进行本地数据存储,但为了简单起见,您可以使用NSUserDefaults。 NSUserDefaults 不适合存储大量数据,因此请谨慎使用它并仅用于用户首选项设置。
如果你还是iOS开发的新手,我建议你在网上阅读更多的资源,这个网站在我早期的iOS开发中帮助了我很多:https://www.raywenderlich.com/ios.
您可以尝试使用下面的代码
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var LastNameTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
var users = [User?]()
var selectedIndexPath = [IndexPath]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.allowsMultipleSelection = true
self.tableView.allowsMultipleSelectionDuringEditing = true
for _ in 0...2 {
users.append(User(finalFirstName: getDemoFirstName(), finalLastName: getDemoLastName()))
}
resetField()
}
func resetField() {
firstNameTextField.text = getDemoFirstName()
LastNameTextField.text = getDemoLastName()
}
func getDemoFirstName() -> String { "FirstName_\(users.count)" }
func getDemoLastName() -> String { "LastName_\(users.count)" }
@IBAction func save(_ sender: Any) {
let finalFirstName = firstNameTextField.text ?? ""
let finalLastName = LastNameTextField.text ?? ""
let user = User(finalFirstName: finalFirstName, finalLastName: finalLastName)
users.append(user)
tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: users.count-1, section: 0)], with: .automatic)
tableView.endUpdates()
resetField()
}
@IBAction func removeCell(_ sender: Any) {
selectedIndexPath.forEach { (indexPath) in
users[indexPath.row] = nil
}
let indexPaths = selectedIndexPath
users = users.filter({ [=10=] != nil })
selectedIndexPath.removeAll()
tableView.beginUpdates()
tableView.deleteRows(at: indexPaths, with: .automatic)
tableView.endUpdates()
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! UserTableViewCell
let user = users[indexPath.row]
cell.fullNameTextField.text = "\(user?.finalFirstName ?? "") \(user?.finalLastName ?? "")"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndexPath.append(indexPath)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
selectedIndexPath = selectedIndexPath.filter({([=10=].row != indexPath.row && [=10=].section != indexPath.section) })
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
users.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
}
}
}
struct User {
let finalFirstName: String
let finalLastName: String
}
class UserTableViewCell: UITableViewCell {
@IBOutlet weak var fullNameTextField: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
UI 设计
我该怎么做才能让用户将名字和姓氏输入到两个单独的文本字段中,然后使用该用户的输入将新单元格添加到 TableView 中(输入位于与table)
我还想知道如何存储从文本字段中获取的数据以保存在设备上并能够被用户删除。
用于制作table的代码:
var finalFirstName = String() // First Name from TextField
var finalLastName = String() // Last Name from TextField
var nameArry = ["Temp User", "Temp User2"] // Array of names used in creating table
这是将上述变量添加到 table:
的代码func createArray() -> [Contacts] {
var tempContact1: [Contacts] = []
if (nameArry.count > 1) {
let contacts = Contacts(MyContact: userName, Me: "Me") // Add the users contact [default is user]
let contacts1 = Contacts(MyContact: nameArry[0], Me: "") // Add First item from nameArry
let contacts2 = Contacts(MyContact: nameArry[1], Me: "") // Add Second item from nameArry
tempContact1.append(contacts)
tempContact1.append(contacts1)
tempContact1.append(contacts2)
return tempContact1
}
else {
let contacts = Contacts(MyContact: userName, Me: "Me")
tempContact1.append(contacts)
return tempContact1
}
}
如有任何帮助,我们将不胜感激。 请注意,该项目已经创建,我不确定我是否有该项目的数据代码。
首先,您在createArray 方法中的逻辑并不理想。您应该循环遍历 nameArry 以动态生成 [Contacts] 数组。你可以简单地做这样的事情:
var finalFirstName = "" // First Name from TextField
var finalLastName = "" // Last Name from TextField
var nameArry = ["Temp User", "Temp User2"]
func createArray() -> [Contacts] {
var tempContact1: [Contacts] = []
tempContact1.append(Contacts(MyContact: userName, Me: "Me"))
for name in nameArry {
tempContact1.append(Contacts(MyContact: name, Me: ""))
}
}
针对你的问题。您需要在 UI 中添加某种完成按钮。如果用户单击它,将新名称添加到您的 nameArry 中,调用 createArray 更新您的 [Contacts] 数组,最后调用 tableview 的 reloadData() 以重新加载数据。您甚至可以通过将 nameArry 设为 Contacts 数组而不是 String 来改进此过程。这样,您将不需要任何映射方法 createArray.
最后,为了保存数据,理想情况下您需要使用Realm 或SQLite 进行本地数据存储,但为了简单起见,您可以使用NSUserDefaults。 NSUserDefaults 不适合存储大量数据,因此请谨慎使用它并仅用于用户首选项设置。
如果你还是iOS开发的新手,我建议你在网上阅读更多的资源,这个网站在我早期的iOS开发中帮助了我很多:https://www.raywenderlich.com/ios.
您可以尝试使用下面的代码
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var LastNameTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
var users = [User?]()
var selectedIndexPath = [IndexPath]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.allowsMultipleSelection = true
self.tableView.allowsMultipleSelectionDuringEditing = true
for _ in 0...2 {
users.append(User(finalFirstName: getDemoFirstName(), finalLastName: getDemoLastName()))
}
resetField()
}
func resetField() {
firstNameTextField.text = getDemoFirstName()
LastNameTextField.text = getDemoLastName()
}
func getDemoFirstName() -> String { "FirstName_\(users.count)" }
func getDemoLastName() -> String { "LastName_\(users.count)" }
@IBAction func save(_ sender: Any) {
let finalFirstName = firstNameTextField.text ?? ""
let finalLastName = LastNameTextField.text ?? ""
let user = User(finalFirstName: finalFirstName, finalLastName: finalLastName)
users.append(user)
tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: users.count-1, section: 0)], with: .automatic)
tableView.endUpdates()
resetField()
}
@IBAction func removeCell(_ sender: Any) {
selectedIndexPath.forEach { (indexPath) in
users[indexPath.row] = nil
}
let indexPaths = selectedIndexPath
users = users.filter({ [=10=] != nil })
selectedIndexPath.removeAll()
tableView.beginUpdates()
tableView.deleteRows(at: indexPaths, with: .automatic)
tableView.endUpdates()
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! UserTableViewCell
let user = users[indexPath.row]
cell.fullNameTextField.text = "\(user?.finalFirstName ?? "") \(user?.finalLastName ?? "")"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndexPath.append(indexPath)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
selectedIndexPath = selectedIndexPath.filter({([=10=].row != indexPath.row && [=10=].section != indexPath.section) })
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
users.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
}
}
}
struct User {
let finalFirstName: String
let finalLastName: String
}
class UserTableViewCell: UITableViewCell {
@IBOutlet weak var fullNameTextField: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
UI 设计