0

[我有这个工作,但我不明白为什么我的“修复”让它工作。]

作为学习练习的一部分,我正在创建一个简单的表格。当用户在表格中选择一个单元格时,我希望它进入第二个 UIViewController。第二个 UIViewController 有一个标签,显示所选单元格中的文本。

“父”类有这个方法来创建子和设置文本:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  child = [[WDRViewControllerFirstChild alloc] initWithNibName:nil bundle:nil];
  child.title = [colors objectAtIndex:indexPath.row];
  child.labelText = [colors objectAtIndex:indexPath.row];
  [self.navigationController pushViewController:child animated:YES];  
}

然后在 WDRViewControllerFirstChild 中,我有两种方法。如果我以这种方式处理它,那么一切正常。

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
      label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 50)];
      colorMap = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil] forKeys:[NSArray arrayWithObjects:@"red", @"green", @"blue", nil]];
//      Adding the subview here won't work.  Why?
//      [self.view addSubview:label];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
  [self.view addSubview:label];
  label.text = labelText;
  label.textAlignment = UITextAlignmentCenter;
  label.backgroundColor = [UIColor whiteColor];
  self.view.backgroundColor = [colorMap objectForKey:labelText];
}

最初,我在 init 调用中将孩子分配给了子视图,但这不起作用。也就是说,文本的标签不会正确显示已选择项目的文本。(它将是空白的。)

我添加了一些 NSLog 调用,另外发现如果我将 addSubview 调用从 viewDidLoad 移动到 init,labelText 的值为 null。但是,在上面的表格中,它已正确设置。

我很高兴它正在工作,但我不明白为什么一个工作而另一个工作。特别是,我真的很困惑为什么根据我调用 addSubview 的位置设置 labelText 起作用。

有什么见解吗?

4

1 回答 1

1

-addSubview仅当视图实际上完全从 XIB 中加载时才会起作用,否则它将调用 nil 并产生 nil。到-initWithNibName:bundle:调用时,操作系统很可能正在解冻(字面意思)您指定的 XIB 并对其进行设置,因此 view 属性为 nil。在-viewDidLoad您可以合理地确定视图的存在,因此大多数设置工作都在此处完成。至于(NULL)标签文本,无论 iVarlabelText是什么,您都没有实例化它。删除该行。

于 2012-05-13T19:24:43.000 回答