在pushViewController之前设置视图控制器属性

时间:2011-10-11 11:46:22

标签: iphone ios ios4 uiviewcontroller uinavigationcontroller

在我的应用中,我已经为视图添加了标签,将其连接到插座,但是当我第一次从另一个视图控制器分配此插座然后调用pushViewController来显示它时,没有显示任何内容。这是在推送显示标签的下一个视图之前的代码:

CustomViewController *vc = [[CustomViewController alloc] init];
vc.lbl_price.text = self.label_price.text; // lbl_price is defined as a property in CustomViewController and label_price is defined in current view controller
[self.navigationController pushViewController:vc];

CustomViewController viewDidLoad方法中,我添加了此说明以查看它是否可行

NSLog(@"Price=%@",lbl_price); // it actually prints out what was previously assigned

但它并没有显示在标签上!

知道为什么吗?

的Stephane

1 个答案:

答案 0 :(得分:18)

即使创建了视图控制器,它的视图层次结构也可能不会(因此所有子视图仍然是零),出于优化原因,在您尝试实际访问控制器视图之前可能无法加载它。您有两种方法可以解决您的问题:

  1. 将所有值存储在单独的非UI变量中,并将它们分配给UI组件,并显示控制器:

    // Before push controller
    vc.myPriceText = self.label_price.text;
    
    // In controller's viewWillAppear:
    self.lbl_price.text = self.myPriceText;
    
  2. 调用[vc view]强制控制器加载其视图层次结构:

     CustomViewController *vc = [[CustomViewController alloc] init];
     [vc view];
     vc.lbl_price.text = self.label_price.text; 
     [self.navigationController pushViewController:vc];