objective-c - 在 UITableView 问题的顶部添加额外的单元格

标签 objective-c ios ipad uitableview nsarray

我已经阅读了一些有关此问题的 SO 帖子,但似乎在向 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]”

最佳答案

我发现了问题。我忽略了一个事实,即我没有考虑其他 UITableView 委托(delegate)方法,并且在为 tableView:canEditRowAtIndexPath 方法设置逻辑时,我没有考虑 UITableView 中的这一额外行。这是解决问题的代码:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // I added code here to intercept the added row (row 0) and make it non-editable
    if([indexPath row] == 0)
    {
        return NO;
    }
    else
    {
        // decrement the row to get the correct object from the self.stringArray    
        int arrayIndex = [indexPath row] - 1;
        if([[self.stringArray objectAtIndex:arrayIndex] length] > 10)
        {
            return YES;
        }
        else
        {
            return NO;
        }
    }
}

关于objective-c - 在 UITableView 问题的顶部添加额外的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8774307/

相关文章:

ios - 如何获取所有包含特定字符串的网址?

ios - 使用推送转场时,主详细信息应用程序立即崩溃

javascript - 使用 PFQuery 检索数组中包含特定项目的 PFInstallation 对象?

ios - 这个错误是什么无效上下文0x0?

objective-c - 如何将具有特殊字符的字符串拆分为 NSMutableArray

iphone - 通过单击按钮替换滑动以删除的操作

iphone - 位置 : fixed doesn't work on iPad and iPhone

ios - 是否可以在 iOS 9 上让您的 iPad 应用程序退出多任务处理

ios - 检测 iPhone 电源按钮按下事件以防止 iOS 中的屏幕截图

objective-c - Xcode 警告 : "May not respond to"