2013-03-17 58 views
2

我有一个简单的UIViewController,它有一个对应的.xib文件。在uiviewcontroller加载后更新xib视图的位置?

ViewController *v = [[ViewController alloc] initWithNibName:@"ViewController" bundle:[NSBundle mainBundle]]; 
[self.navigationController pushViewController:v animated:YES]; 

在此的.xib文件,我有一个UILabel,其被定位在屏幕的中间。我想一旦视图被加载到这个标签移动到新的位置,但在此之前它是可见:

label.center = CGPointMake(0,0); 

当我尝试把上面的代码在下面的方法,这是发生了什么:

  • initWithNibName:bundle:位置不更新
  • awakeFromNib:位置不更新
  • viewDidLoad:位置不更新
  • viewWillAppear:位置不更新
  • viewDidAppear:位置仅在视图完全加载后才会更新(即,标签的原始位置可以在瞬间看到)。

,当我尝试更新的东西,如文本属性:

label.text = @"Foo"; 

...它适用于所有的这些方法。出于某种原因,它只是被.xib文件覆盖的位置。

当我说“位置不更新”时,我的意思是当屏幕上显示标签时,它位于.xib文件中定义的位置,而不是我试图覆盖它的位置。

当我尝试NSLog的位置时,它表明它正确更新它,但是当我再次检查位置viewDidAppear时,它显示不正确的值。例如,说的.xib在99定义了X,我想将它更改为0:

- (void)viewWillAppear:(BOOL)animated { 
    label.center = CGPointMake(0,0); 
    NSLog(@"%f", label.center.x); // reports 0 
} 

- (void)viewDidAppear:(BOOL)animated { 
    NSLog(@"%f", label.center.x); // reports 99 (Error: should be 0) 
    label.center = resultLabelHiddenCenter; 
    NSLog(@"%f", label.center.x); // reports 0 
} 

如何我可以更新标签的中心,没有任何毛刺视觉显示视图前?

+0

您是否在使用autolayout? – 2013-03-17 06:55:06

回答

5

我认为,您正在为您的xib使用autoLayout

enter image description here

我对你有两种解决方案在我的脑海里。

第一个是,请不要使用setFramesetBounds因为Autolayout会跳过他们。

更改约束是最好的解决方案。您还可以添加/删除额外的约束。

有关Autolayout调整的好视频tutorial可在WWDC 2012中找到。

enter image description here

第二个是,实现viewDidLayoutSubviews它将调用调用视图控制器的视图的layoutSubviews方法之后。

- (void)viewDidLayoutSubviews 
{ 
    @try 
    { 
     // reset label frame here. 
    } 
    @catch (NSException *exception) 
    { 
     NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]); 
    } 
} 
相关问题