我正在创建一个演示应用程序,其中在tableView中需要3个customCells。我能够在所有三行中添加第一个customCell,但是当我添加3个单元时,应用程序崩溃。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Create Rows in a tableView
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"customCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
// First CustomCell
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FirstCustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
if (indexPath.row ==1) {
// Second CustomCell
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (indexPath.row == 2) {
// Third CustomCell
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PhoneTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:1];
}
}
return cell;
}
当我运行应用程序时,它崩溃了,这是错误消息:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
最佳答案
问题是 cell = [nib objectAtIndex:1]; 必须始终为 cell = [nib objectAtIndex:0]; ,因为该名称只有一个笔尖
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"customCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
// First CustomCell
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FirstCustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
if (indexPath.row ==1) {
// Second CustomCell
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (indexPath.row == 2) {
// Third CustomCell
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PhoneTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
}
return cell;
}
关于ios - 我如何在TableView中添加多个customCells(在我的情况下为3),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25154199/