如何在 Swift 中将新单元格插入 UITableView [英] How to insert new cell into UITableView in Swift

查看:28
本文介绍了如何在 Swift 中将新单元格插入 UITableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 textField should go into the tableView and the second go into the second tableView. My problem is that I don't know how to put data in the tableView each 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 tableView each time the user hits the button?

推荐答案

使用 beginUpdatesendUpdates 在按钮被点击时插入一个新单元格.

Use beginUpdates and endUpdates to insert a new cell when the button clicked.

正如@vadian 在评论中所说,begin/endUpdates 对单个插入/删除/移动操作没有影响

As @vadian said in comment, begin/endUpdates has no effect for a single insert/delete/move operation

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

First of all, append data in your tableview array

Yourarray.append([labeltext])  

然后更新您的表格并插入一个新行

Then update your table and insert a new row

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

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

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

Swift 3.0

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


目标 C

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

这篇关于如何在 Swift 中将新单元格插入 UITableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆