在 UITableView 问题顶部添加额外的单元格
我读过一些关于这个问题的帖子,但似乎遇到了问题(当然包括拉头发),在 UITableView 的顶部添加一个额外的单元格。这是我的代码:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// self.StringArray has 5 string objects inside
return ([self.stringArray count] + 1);
}
- (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];
}
// create hardcoded first row in table
if([indexPath row] == 0)
{
cell.textLabel.text = @"Select me";
}
else
{
// decrement the row to get the correct object from the self.stringArray
int arrayIndex = [indexPath row] - 1;
cell.textLabel.text = [self.stringArray objectAtIndex:arrayIndex];
}
return cell;
}
一切看起来都不错(如果我收到异常错误,显然有些问题),但我似乎无法注视它。
异常:* 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“* -[__NSArrayM objectAtIndex:]:索引 5 超出范围 [0 .. 4]”
I've read a few SO posts regarding this issue, but seem to be having issues (hair pulling included of course) adding an additional cell to the top of a UITableView. Here is my code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// self.StringArray has 5 string objects inside
return ([self.stringArray count] + 1);
}
- (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];
}
// create hardcoded first row in table
if([indexPath row] == 0)
{
cell.textLabel.text = @"Select me";
}
else
{
// decrement the row to get the correct object from the self.stringArray
int arrayIndex = [indexPath row] - 1;
cell.textLabel.text = [self.stringArray objectAtIndex:arrayIndex];
}
return cell;
}
Everything looks good (obviously something is wrong though if I'm getting exception error), but I can't seem to eyeball it.
Exception: * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现了问题。我忽略了这样一个事实:我没有考虑其他 UITableView 委托方法,并且在设置 tableView:canEditRowAtIndexPath 方法的逻辑时,也没有考虑 UITableView 中的这一额外行。这是解决问题的代码:
I found the problem. I overlooked the fact that I didn't account for the other UITableView delegate methods, and I didn't account for this extra row in the UITableView when setting up the logic for the tableView:canEditRowAtIndexPath method. Here is the code that fixed the problem: