ios 以编程方式将单元格添加到 UITableView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9429618/
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
Adding cells programmatically to UITableView
提问by KerrM
I've just recently started programming for the iPhone and I'm making an application that connects to a database and gets a set of row names and displays them. When selected, the rows background colour change ie you can make multiple selections and they will all be different colours. So I'm getting the XML back from the server no problem and I have created a UITableView
to display the cells in. However, I have no idea how to add the cells into the table. I had a look at insertRowsAtIndexPaths
but I'm not sure how to use it? As I understand, insertRowsAtIndexPaths
takes two parameters:
我最近刚刚开始为 iPhone 编程,我正在制作一个连接到数据库并获取一组行名称并显示它们的应用程序。选中后,行的背景颜色会发生变化,即您可以进行多项选择,它们都将是不同的颜色。所以我从服务器获取 XML 没问题,我已经创建了一个UITableView
来显示单元格。但是,我不知道如何将单元格添加到表格中。我看了看,insertRowsAtIndexPaths
但我不知道如何使用它?据我了解,insertRowsAtIndexPaths
需要两个参数:
An NSArray that contains what row the cell is supposed to be in and in what section. The problem with this is that my app will have a dynamic number of rows. How would I go about creating the NSArray if I don't know how many rows I will have? Can I use NSMutableArray?
一个 NSArray,包含单元格应该在哪一行以及在哪个部分。问题在于我的应用程序将具有动态行数。如果我不知道我将有多少行,我将如何创建 NSArray?我可以使用 NSMutableArray 吗?
The second parameter it takes is an animation - that's pretty straightforward.
它需要的第二个参数是动画——这非常简单。
Another issue I am having is where do I actually create the cells? How do you pass the cells to the tableview?
我遇到的另一个问题是我实际上在哪里创建单元格?你如何将单元格传递给tableview?
I've tried reading the documentation but it just doesn't seem very clear! Here is the code I have at the moment inside the loadview method of the 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];
回答by Will Pragnell
I think you're approaching this from the wrong direction. UITableViews don't work as you are expecting. insertRowsAtIndexPaths
is for inserting new rows into a table, rather than for populating it in the first instance.
我认为你从错误的方向接近这个。UITableViews 不能像你期望的那样工作。insertRowsAtIndexPaths
用于向表中插入新行,而不是在第一个实例中填充它。
UITableViews work by calling a number of delegate methods that allow you to present your data to the table view as you need to. The framework then takes care of the heavy lifting to populate cells, handle scrolling and touch events, etc.
UITableViews 通过调用许多委托方法来工作,这些方法允许您根据需要将数据呈现给表格视图。然后框架负责填充单元格、处理滚动和触摸事件等繁重的工作。
I would recommend that you start by reading a tutorial such as this one: http://www.iosdevnotes.com/2011/10/uitableview-tutorial/, which looks fairly thorough to me. It explains how to set your datasource for the table and how you can configure the way your data is presented by the UITableView.
我建议您从阅读这样的教程开始:http: //www.iosdevnotes.com/2011/10/uitableview-tutorial/,对我来说看起来相当彻底。它解释了如何为表设置数据源以及如何配置 UITableView 呈现数据的方式。
Good luck!
祝你好运!
回答by Frade
Don't need to use insertRowsAtIndexPaths
.
不需要使用insertRowsAtIndexPaths
.
Check: UITableViewDataSource Protocol Referenceand UITableView Class Reference
检查:UITableViewDataSource 协议参考和UITableView 类参考
The magic happens between this three methods (UITableViewDataSource protocol methods):
这三种方法(UITableViewDataSource 协议方法)之间发生了神奇的事情:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
You just need to fill an array. Yes it can be a NSMutableArray
.
你只需要填充一个数组。是的,它可以是NSMutableArray
.
You can fill the array in - (void)viewDidLoad
, for example:
您可以在 中填充数组- (void)viewDidLoad
,例如:
yourItemsArray = [[NSMutableArray alloc] initWithObjects:@"item 01", @"item 02", @"item 03", nil];
And them use the data source methods like this:
他们使用这样的数据源方法:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
// If You have only one(1) section, return 1, otherwise you must handle sections
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [yourItemsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.textLabel.text = [yourItemsArray objectAtIndex:indexPath.row];
return cell;
}
Like this cells will be created automatically.
这样单元格将自动创建。
If You chage the Array, just need to call:
如果你改变数组,只需要调用:
[self.tableView reloadData];
回答by Sandip Patel - SM
//######## Adding new section programmatically to UITableView ############
@interface MyViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
{
IBOutlet UITableView *tblView;
int noOfSection;
}
-(IBAction)switchStateChanged:(id)sender;
@end
@implementation MyViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad{
[super viewDidLoad];
noOfSection = 2;
}
- (void)viewDidUnload{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
return YES;
}
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark - TableView Delegate Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return noOfSection;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if(indexPath.section == 2){
return 200;
}
return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
UISwitch *switchBtn = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 20, 10)];
cell.accessoryView = switchBtn;
[switchBtn addTarget:self action:@selector(switchStateChanged:) forControlEvents:UIControlEventValueChanged];
cell.textLabel.font = [UIFont systemFontOfSize:14];
cell.detailTextLabel.font = [UIFont systemFontOfSize:11];
cell.textLabel.numberOfLines = 2;
cell.detailTextLabel.numberOfLines = 2;
}
if(indexPath.section == 0){
cell.textLabel.text = @"Cell-1 Text";
cell.detailTextLabel.text = @"Cell-1 Detail text";
}
else if(indexPath.section == 1){
cell.textLabel.text = @"Cell-2 Text";
}
else { // new added section code is here...
cell.textLabel.text = @"New Added section";
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
-(IBAction)switchStateChanged:(id)sender{
UISwitch *switchState = sender;
if(switchState.isOn == YES){
NSLog(@"ON");
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
[self insertNewSectionWithIndexPath:indexPath];
}
else {
NSLog(@"OFF");
[self removeSectionWithIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
}
}
-(void)insertNewSectionWithIndexPath:(NSIndexPath *)indexPath{
noOfSection = 3;
[tblView insertSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationFade];
}
-(void)removeSectionWithIndexPath:(NSIndexPath *)indexPath{
noOfSection = 2;
[tblView deleteSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationFade];
}
@end
回答by fibnochi
You need not to worry about it. cells will be created automatically. just look at these UITableview Class Reference
你不必担心。将自动创建单元格。看看这些 UITableview 类参考
You have to implement UITableView dataSource and delegate Protocol. Also look at this tutorial UITableview Tutorial
您必须实现 UITableView 数据源和委托协议。也看看这个教程 UITableview Tutorial