Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีเพิ่ม Cell ใหม่เข้า UITableView ใน Swift

เพิ่ม Cell ใหม่ใน UITableView ใช้ insertRows(at:with:) พร้อมอัปเดต Data Source

ขั้นตอนพื้นฐาน

  1. อัปเดต Data Array (เพิ่มข้อมูล)
  2. เรียก tableView.insertRows(at: [indexPath], with: .automatic)

โค้ดตัวอย่าง


class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var tableView: UITableView!
    var items = ["Item 1", "Item 2", "Item 3"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }
    
    // DataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = items[indexPath.row]
        return cell
    }
    
    // เพิ่ม Cell ใหม่
    @IBAction func addItem(_ sender: UIBarButtonItem) {
        let newItem = "Item \(items.count + 1)"
        items.append(newItem)
        
        let indexPath = IndexPath(row: items.count - 1, section: 0)
        tableView.insertRows(at: [indexPath], with: .automatic)
    }
    
    // เพิ่มหลาย Cell พร้อมกัน
    func addMultipleItems(_ newItems: [String]) {
        let startIndex = items.count
        items.append(contentsOf: newItems)
        
        let indexPaths = (startIndex..

Animation Options

  • .automatic - Default, เลือกอัตโนมัติ
  • .fade - จางเข้า/ออก
  • .right, .left, .top, .bottom - Slide จากทิศทาง
  • .middle - ขยายจากกลาง
  • .none - ไม่มี Animation

การลบ Cell


func deleteItem(at indexPath: IndexPath) {
    items.remove(at: indexPath.row)
    tableView.deleteRows(at: [indexPath], with: .automatic)
}

// Swipe to Delete
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        deleteItem(at: indexPath)
    }
}

Batch Updates (iOS 11+)


tableView.performBatchUpdates({
    // Insert, Delete, Reload หลายอย่างพร้อมกัน
    tableView.insertRows(at: newIndexPaths, with: .automatic)
    tableView.deleteRows(at: oldIndexPaths, with: .automatic)
}, completion: nil)

Custom Cell

สร้าง CustomCell.swift + CustomCell.xib หรือ Prototype Cell ใน Storyboard → Register: tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")