【问题标题】:Passing data using UINavigationController使用 UINavigationController 传递数据
【发布时间】:2012-05-13 19:14:45
【问题描述】:

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

作为学习练习的一部分,我正在创建一个简单的表格。当用户在表格中选择一个单元格时,我希望它进入第二个 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 起作用。

有什么见解吗?

【问题讨论】:

    标签: iphone ios uiviewcontroller uinavigationcontroller


    【解决方案1】:

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

    【讨论】:

    • 谢谢。我相信这解释了为什么我不能从 init 调用 addSubview。一般情况下很高兴知道。但是,我不明白为什么这会影响我设置 labelText 的能力。这是一个定义的属性和合成的。一旦我实例化了 WDRViewControllerFirstChild 的实例,我应该能够设置它的属性吗?
    • 想通了。 viewDidLoad 在我设置它的语句之前被调用(即 child.labelText = [colors objectAtIndex:indexPath.row])。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 2017-02-18
    • 1970-01-01
    相关资源
    最近更新 更多