简体   繁体   中英

Adding content to a TableView Swift IOS

How can I make is so a user can input a first and last name into two separate text fields and use the input from that user to add a new cell into the TableView (Input is inside of a different view than the table)

I would also like to know how I can store the data gotten from the text field to be saved on device and able to be removed by the user.

Code Used to make the 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

This is the code that adds the variables above to the 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
    }
}

Any help would be greatly appreciated. Just a note, the project is already created and im unsure if I have data code on the project.

First, your logic in createArray method is not ideal. You should loop through nameArry to generate your [Contacts] array dynamically. You can simply do something like this:

    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: ""))
        }
    }

For your question. You need to add some sort of Done button in your UI. If the user clicks this, add the new name in your nameArry, call createArray to update your [Contacts] array, and finally call reloadData() of your tableview to reload the data. You can even improve this process by making your nameArry to a Contacts array instead of String. This way, you won't need any mapping method createArray.

And lastly for saving data, ideally you need to use Realm or SQLite for local data storage, but for simplicity, you can use NSUserDefaults. NSUserDefaults is not ideal for storing large amounts of data so use this sparingly and for User Preference settings only.

If you are still new to iOS development, I suggest you read more resources on the internet, this site helped me a lot in my early years in iOS development: https://www.raywenderlich.com/ios .

You can try with this code below

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({ $0 != 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({($0.row != indexPath.row && $0.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 Design

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM