我最近刚开始为 iPhone 编程,我正在制作一个连接到数据库并获取一组行名称并显示它们的应用程序。选择后,行的背景颜色会发生变化,即您可以进行多项选择,它们都将是不同的颜色。所以我从服务器获取 XML 没问题,我创建了一个 UITableView
来显示其中的单元格。但是,我不知道如何将单元格添加到表格中。我查看了 insertRowsAtIndexPaths
但我不确定如何使用它?据我了解,insertRowsAtIndexPaths
有两个参数:
一个 NSArray,包含单元格应该在哪一行以及在哪一节。问题在于我的应用程序将具有动态行数。如果我不知道我将拥有多少行,我将如何着手创建 NSArray?我可以使用 NSMutableArray 吗?
它采用的第二个参数是动画 - 这非常简单。
我遇到的另一个问题是我实际上在哪里创建单元格?如何将单元格传递给表格 View ?
我已经尝试阅读文档,但似乎不是很清楚!这是我目前在 View Controller 的 loadview 方法中的代码:
//Before this I get the XML from the server so I am ready to populate
//cells and add them to the table view
NSArray *cells = [NSArray arrayWithObjects:
[NSIndexPath indexPathForRow:0 inSection:0],
[NSIndexPath indexPathForRow:1 inSection:0],
[NSIndexPath indexPathForRow:2 inSection:0],
[NSIndexPath indexPathForRow:3 inSection:0],
[NSIndexPath indexPathForRow:4 inSection:0],
[NSIndexPath indexPathForRow:5 inSection:0],
[NSIndexPath indexPathForRow:6 inSection:0],
[NSIndexPath indexPathForRow:7 inSection:0],
[NSIndexPath indexPathForRow:8 inSection:0],
[NSIndexPath indexPathForRow:9 inSection:0],
[NSIndexPath indexPathForRow:10 inSection:0],
[NSIndexPath indexPathForRow:11 inSection:0],
[NSIndexPath indexPathForRow:12 inSection:0],
nil];
[eventTypesTable beginUpdates];
[eventTypesTable insertRowsAtIndexPaths:cells withRowAnimation:UITableViewRowAnimationNone];
[eventTypesTable endUpdates];
最佳答案
我认为您是从错误的方向来处理这个问题的。 UITableViews 没有像您期望的那样工作。 insertRowsAtIndexPaths
用于将新行插入表中,而不是在第一个实例中填充它。
UITableViews 通过调用许多委托(delegate)方法来工作,这些方法允许您根据需要将数据呈现给 TableView 。然后,该框架负责繁重的工作以填充单元格、处理滚动和触摸事件等。
我建议您先阅读如下教程:http://www.iosdevnotes.com/2011/10/uitableview-tutorial/ ,这对我来说看起来相当彻底。它解释了如何为表设置数据源以及如何配置 UITableView 显示数据的方式。
祝你好运!
关于ios - 以编程方式将单元格添加到 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9429618/