0

I am initializing a new UIViewCOntroller object. then attempting to set its view's position of stage but I am having some trouble.

here is the code I am using Note: this code is placed in the application main UIViewController's viewDidLoad method

UIViewController * cont = [[UIViewController alloc] init];  
    cont.view.backgroundColor = [UIColor redColor];  
    CGRect rect = CGRectMake(100, 0, 320, 480);  
    cont.view.frame = rect;  

this code is still positioning the subview at (0,0) instead of (100,0) However, if I introduce a decimal, such as using 320.01 (for the width value) or 480.01 (for the height value). The view would be positioned correctly.

It seems that if I use a size with an exact width:320.0 height: 480.0, the origin will always be set to (0,0) !!!

This is a bit strange. I was hoping that someone could explain why this is happening, and possibly how it may be resolved.

Cheers ....

4

3 回答 3

1

NSLog cont.view 的值,我想你会发现它是 nil,这就解释了为什么什么都没发生。这不是创建 UIViewController 的常规方法——以编程方式创建一个并没有,但 99.99% 的时间 UIViewController 子类是使用 .xib 文件中的主 UIView 创建的。一个新创建的 UIViewController 对象有一个 nil "view" 成员,所以你必须以某种方式初始化它,或者通过加载一个 .xib:

MyViewController *vc = [[[MyViewController alloc] initWithNibName@"MyViewController" bundle:nil] autorelease];

或手动创建视图:

MyViewController *vc = [[[MyViewController alloc] init] autorelease];
UIView *theView = [[[UIView alloc] initWithFrame:viewframe] autorelease];
vc.view = theView;

然后您可以将视图的框架移动到您想要的内容,但是移动视图控制器的基本视图通常不是您想要做的,您想要创建子视图并移动它们。

于 2011-02-11T15:21:23.730 回答
0

我想你应该可以使用

-(void) loadView { 
  [super loadView];
  //create your views programmatically here
}

为了以编程方式创建您的 viewController 并避免 IB。通常,当您的“视图”属性为零时,IB 会为您调用此方法,但是如果您避免使用 IB,请确保包含上述方法,以便您的视图属性不为零。

于 2011-02-11T19:08:54.280 回答
0

[[UIViewController alloc]init]是错的。UIViewController 的指定初始化程序是initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle. 即使这样也不一定会view立即将插座初始化为实际的 UIView。您需要继承 UIViewController 并在viewDidLoad该子类的方法中执行您的自定义。

在此期间很可能view是这样,nil因此您可以尝试设置您喜欢的任何属性,而不会发生任何事情。

于 2011-02-11T15:21:14.453 回答