You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从另一个ViewController向TableView添加行且避免覆盖数据

Hey Ahmed, let's fix that frustrating issue where your table view only shows one row no matter how many entries you add! This is almost always a problem with how you're storing or updating your data source—let's break down the fixes step by step.

First: Check Your Data Source Structure

The root cause here is probably that you're using a single variable (like var currentName: String? and var currentLink: String?) instead of an array to store multiple entries. You need a collection that can hold all your name-link pairs.

Start by creating a simple model to organize your data (way cleaner than using dictionaries):

struct LinkEntry {
    let name: String
    let link: String
}

Then in your TableViewController, declare an array to hold all entries:

var linkEntries = [LinkEntry]()

Fix the Save Button Logic

When your popup's save button is tapped, you need to append the new entry to the array—not replace the entire array. Here's how that might look in your popup view controller:

@IBAction func saveTapped(_ sender: UIButton) {
    // Validate input first
    guard let name = nameTextField.text?.trimmingCharacters(in: .whitespaces), !name.isEmpty,
          let link = linkTextField.text?.trimmingCharacters(in: .whitespaces), !link.isEmpty else {
        // Show an alert if fields are empty (optional but helpful)
        let alert = UIAlertController(title: "Oops!", message: "Please fill in both fields.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
        return
    }

    // Create the new entry
    let newEntry = LinkEntry(name: name, link: link)
    
    // Pass the entry back to your TableViewController
    if let tableVC = presentingViewController as? YourTableViewControllerName {
        // Append the new entry—DO NOT set linkEntries = [newEntry] (that replaces everything!)
        tableVC.linkEntries.append(newEntry)
        // Save the data if you want it to persist (we'll cover that next)
        tableVC.saveEntries()
        // Refresh the table view to show the new row
        tableVC.tableView.reloadData()
    }

    dismiss(animated: true)
}

Make Sure Your Table View Data Source Methods Are Correct

Double-check these two critical methods in your TableViewController—they're often where mistakes happen:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the count of your array, NOT a fixed number like 1!
    return linkEntries.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID", for: indexPath)
    let entry = linkEntries[indexPath.row]
    // Populate your cell with the entry data
    cell.textLabel?.text = entry.name
    cell.detailTextLabel?.text = entry.link // Or use custom cell outlets if you have them
    return cell
}

Optional: Add Persistence (So Data Stays After App Restart)

If you want your entries to stick around when the app closes, add these methods to your TableViewController:

func saveEntries() {
    do {
        let encodedData = try JSONEncoder().encode(linkEntries)
        UserDefaults.standard.set(encodedData, forKey: "SavedLinkEntries")
    } catch {
        print("Failed to save entries: \(error.localizedDescription)")
    }
}

func loadEntries() {
    guard let savedData = UserDefaults.standard.data(forKey: "SavedLinkEntries") else { return }
    do {
        linkEntries = try JSONDecoder().decode([LinkEntry].self, from: savedData)
        tableView.reloadData()
    } catch {
        print("Failed to load entries: \(error.localizedDescription)")
    }
}

Then call loadEntries() in your viewDidLoad() method to restore saved data when the screen loads.

Common Pitfalls to Avoid

  • Replacing the array instead of appending: Using linkEntries = [newEntry] wipes out all old data—always use append() or insert(_:at:).
  • Hardcoding row count: If numberOfRowsInSection returns 1, your table will never show more than one row, no matter how much data you have.
  • Forgetting to reload the table: After updating your data source, you must call tableView.reloadData() to tell the table to refresh its content.

That should fix your issue—you'll be adding multiple rows in no time!

内容的提问来源于stack exchange,提问作者Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:10:13