【问题标题】:Adding additional cell to top of UITableView Issues在 UITableView 问题顶部添加其他单元格
【发布时间】:2012-01-08 00:18:12
【问题描述】:

我已经阅读了一些关于此问题的 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:]: index 5 beyond bounds [0 .. 4]”

【问题讨论】:

  • 您是否在 '- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath ' 方法的末尾返回单元格?
  • @KrishnaK - 它看起来像一个糟糕的复制/粘贴,所以我将它添加到代码示例中。它存在于我的原始代码中。
  • 我在 xcode 中试过了,你的代码执行没有任何异常。据我所知,从这段代码中,stringArray 的内容在上面的两个调用之间被修改了。返回 numberOfRowsInSection 时尝试检查计数值。
  • @KrishnaK - 请参阅下面的答案 =)

标签: objective-c ios ipad uitableview nsarray


【解决方案1】:

我发现了问题。我忽略了一个事实,即我没有考虑其他 UITableView 委托方法,并且在设置 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;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-12-22
    • 2016-05-30
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多