在UITableView的迅速同时添加两行(Adding two rows simultaneous

2019-09-29 09:42发布

对不起,我是很新的快捷。 我想在我的阵列添加两个或多个项目animalsList同时,在我的tableview做一个更新。 我如何分配我的indexPath有两个的indeces? 我试图寻找答案在这里,但我找不到任何。

如何更新表视图,如果我添加更多的商品?

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var animalsList = ["dog", "cat", "pig"];

@IBOutlet weak var tableView: UITableView!

@IBAction func click(_ sender: Any) {
    animalsList.append("horse");
    animalsList.append("mouse");

    let indexPath = IndexPath(row: animalsList.count - 1, section: 0);
    tableView.beginUpdates();
    tableView.insertRows(at: [indexPath], with: .none);
    tableView.endUpdates();

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return animalsList.count;
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .default, reuseIdentifier: "cell");
    cell.textLabel?.text = animalsList[indexPath.row];
    return cell;
}

Answer 1:

对于插入同时在两行UITableView你可以做到这样。

@IBAction func click(_ sender: Any) {

    animalsList.append("horse")
    animalsList.append("mouse")

    var Arr_indexPath = [IndexPath]()

    Arr_indexPath.append(IndexPath(row: animalsList.index(of: "horse")!, section: 0))
    Arr_indexPath.append(IndexPath(row: animalsList.index(of: "mouse")!, section: 0))
    tableView.insertRows(at: Arr_indexPath, with: .none)
}


Answer 2:

请确保您已连接表视图的委托和数据源成功。

@IBAction func click(_ sender: Any) {
    animalsList.append("horse")
    animalsList.append("mouse")
    tableView.reloadData()
}


Answer 3:

首先,你需要把这两行你viewDidLoad中()

tableView.dataSource = self
tableView.delegate = self

然后,你可以简单地只需将物品放入您的阵列和重新加载的tableView,它会自动再次重申,在阵列,看到了新的价值观

animalsList.append('horse')
tableView.reloadData()


文章来源: Adding two rows simultaneously in uitableview swift