ios 如何在 Swift 中将新单元格插入 UITableView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31870206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:10:45  来源:igfitidea点击:

How to insert new cell into UITableView in Swift

iosiphoneswiftuitableview

提问by code Horizons

I'm working on a project where I have two UITableViews and two UITextFields, when the user presses the button the data in the first textFieldshould go into the tableViewand the second go into the second tableView. My problem is that I don't know how to put data in the tableVieweach time the user pushes the button, I know how to insert data with tableView:cellForRowAtIndexPath:but that works for one time as far as I know. So what method can I use to update the tableVieweach time the user hits the button?

我正在做一个项目,我有两个UITableViews 和两个UITextFields,当用户按下按钮时,第一个中的数据textField应该进入tableView,第二个进入第二个tableView。我的问题是,我不知道如何tableView在用户每次按下按钮时将数据放入,我知道如何插入数据,tableView:cellForRowAtIndexPath:但据我所知,这一次有效。那么tableView每次用户点击按钮时我可以使用什么方法来更新?

回答by EI Captain v2.0

Use beginUpdatesand endUpdatesto insert new cell when button clicked.

单击按钮时使用beginUpdatesendUpdates插入新单元格。

First of all append data in your tableview array

首先在你的 tableview 数组中追加数据

Yourarray.append([labeltext])  

Then upate your table and insert new row

然后upate你的表并插入新行

// Update Table Data
tblname.beginUpdates()
tblname.insertRowsAtIndexPaths([
NSIndexPath(forRow: Yourarray.count-1, inSection: 0)], withRowAnimation: .Automatic)
tblname.endUpdates()

This inserts cell and doesn't need to reload whole table but if you get any problem with this, you can also use tableview.reloadData()

这会插入单元格并且不需要重新加载整个表格,但是如果您对此有任何问题,您也可以使用 tableview.reloadData()



Swift 3.0

斯威夫特 3.0

tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: yourArray.count-1, section: 0)], with: .automatic)
tableView.endUpdates()


Objective-C

目标-C

[self.tblname beginUpdates];
NSArray *arr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:Yourarray.count-1 inSection:0]];
[self.tblname insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tblname endUpdates];

回答by Sourabh Sharma

Swift 5.0, 4.0, 3.0Updated Solution

Swift 5.0、4.0、3.0更新解决方案

Insert at Bottom

在底部插入

self.yourArray.append(msg)

self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: self.yourArray.count-1, section: 0)], with: .automatic)
self.tblView.endUpdates()

Insert at Top of TableView

在 TableView 顶部插入

self.yourArray.insert(msg, at: 0)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
self.tblView.endUpdates()

回答by Dharmesh Kheni

Here is your code for add data into both tableView:

这是将数据添加到两个 tableView 的代码:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var table1Text: UITextField!
    @IBOutlet weak var table2Text: UITextField!
    @IBOutlet weak var table1: UITableView!
    @IBOutlet weak var table2: UITableView!

    var table1Data = ["a"]
    var table2Data = ["1"]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func addData(sender: AnyObject) {

        //add your data into tables array from textField
        table1Data.append(table1Text.text)
        table2Data.append(table2Text.text)

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //reload your tableView
            self.table1.reloadData()
            self.table2.reloadData()
        })


        table1Text.resignFirstResponder()
        table2Text.resignFirstResponder()
    }

    //delegate methods
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == table1 {
            return table1Data.count
        }else if tableView == table2 {
            return table2Data.count
        }
        return Int()
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        if tableView == table1 {
            let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table1Data[row]

            return cell
        }else if tableView == table2 {

            let cell = table2.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table2Data[row]

            return cell
        }

        return UITableViewCell()
    }
}

And your result will be:

你的结果将是:

enter image description here

在此处输入图片说明

回答by Shourob Datta

For Swift 5

对于 Swift 5

Remove Cell

删除单元格

    let indexPath = [NSIndexPath(row: yourArray-1, section: 0)]
    yourArray.remove(at: buttonTag)
    self.tableView.beginUpdates()

    self.tableView.deleteRows(at: indexPath as [IndexPath] , with: .fade)
    self.tableView.endUpdates()
    self.tableView.reloadData()// Not mendatory, But In my case its requires

Add new cell

添加新单元格

    yourArray.append(4)

    tableView.beginUpdates()
    tableView.insertRows(at: [
        (NSIndexPath(row: yourArray.count-1, section: 0) as IndexPath)], with: .automatic)
    tableView.endUpdates()