ios - [[self.effectsTableView cellForRowAtIndexPath :indexPath]. textLabel text] 在 didSelectRowAtIndexPath 上返回 nil

标签 ios objective-c uitableview

didSelecctRowAtIndexPath方法如下:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.currSelectedRowTitle = [[self.effectsTableView cellForRowAtIndexPath:indexPath].textLabel text];
    [self performSegueWithIdentifier:@"PushedByTableView" sender:self];
}

cellForRowAtIndexPath 如下:

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.effectsArray)
    {
        [self loadEffectsInArray];
    }

    static NSString *cellIdentifier = @"EffectsCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }

    //6
    Effect *effectCellEffect = [self.effectsArray objectAtIndex:indexPath.row];
    NSString *effectCellText = effectCellEffect.name;
    //7
    [cell.textLabel setText:effectCellText];
    //[cell.detailTextLabel setText:@"5 stars!"];
    cell.textLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
    //cell.backgroundColor = [UIColor blackColor];
    //cell.textLabel.textColor = [UIColor whiteColor];
    //cell.detailTextLabel.textColor = [UIColor grayColor];
    //cell.textLabel.highlightedTextColor = self.effectsTableView.tintColor;

    return cell;
}

问题是 [[self.effectsTableView cellForRowAtIndexPath:indexPath].textLabel text] 在 didSelectRowAtIndexPath 上返回 nil。有什么问题吗?

最佳答案

您不应该以这种方式使用单元格。数据应该只放在单元格中,以便它可以显示它。您永远不应该使用 View 来存储数据,然后再检索它。

在您的代码中您正在做...

Effect *effectCellEffect = [self.effectsArray objectAtIndex:indexPath.row];
NSString *effectCellText = effectCellEffect.name;

cell.textLabel.text = effectCellText;

所以在 didSelectRow 中做同样的事情...

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Effect *effectCellEffect = [self.effectsArray objectAtIndex:indexPath.row];
    self.currSelectedRowTitle = effectCellEffect.name;
    [self performSegueWithIdentifier:@"PushedByTableView" sender:self];
}

然后你可以通过重构将它提取到一个函数中,因为你在两个地方做同样的事情,但我会把它留给你。

关于ios - [[self.effectsTableView cellForRowAtIndexPath :indexPath]. textLabel text] 在 didSelectRowAtIndexPath 上返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22906134/

相关文章:

ios - 发射器不随父节点旋转

ios - 后台 CallKit 音频初始化错误 - 第一次通话后音频无法正常工作

ios - 在 UIView 中包含 UIViewController

iphone - NSString boundingRectWithSize 使用 CoreText Framesetter 切割高度短? iOS

ios - 模拟器中的 Logo 大小已更改

ios - 用户完成编辑 uitextfield 后调用prepareforsegue

iOS 7 风格的模糊 View

ios - 如何在重置之前向日志添加值(Swift 中的 CoreData)

ios - 使用 UITableViewAutomaticDimension 在顶部插入行时保持 UITableView 偏移

iOS:使用 Storyboard在两个 UITableViewController 之间传递数据