2013-10-18 290 views
1

我想創建一個具有自動佈局按鈕的UIViewController。 (與WWDC 2012會話202中的相同)此視圖控制器被推入UINavigationController。使用自動佈局以編程方式創建UIViewController

我根本不想使用故事板。一切都必須以編程方式完成。

問題是如何設置視圖控制器的主視圖的尺寸,以便它具有屏幕的大小?

我的視圖控制器看起來是這樣的:

@implementation EAViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.view.backgroundColor = [UIColor blueColor]; 
    UIView * superview = self.view; 
    UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [button setTitle:@"Button" forState:UIControlStateNormal]; 

    [superview addSubview:button]; 

    NSLayoutConstraint * cn = [NSLayoutConstraint constraintWithItem:button 
                  attribute:NSLayoutAttributeCenterX 
                  relatedBy:NSLayoutRelationEqual 
                   toItem:self.view 
                  attribute:NSLayoutAttributeCenterX 
                  multiplier:1.0 
                  constant:0.0]; 

    [self.view addConstraint: cn]; 

    cn = [NSLayoutConstraint constraintWithItem:button 
             attribute:NSLayoutAttributeBottom 
             relatedBy:NSLayoutRelationEqual 
             toItem:self.view 
             attribute:NSLayoutAttributeBottom 
            multiplier:1.0 
             constant:-20]; 

    [self.view addConstraint:cn]; 

    [self.view setTranslatesAutoresizingMaskIntoConstraints:NO]; 
    [button setTranslatesAutoresizingMaskIntoConstraints:NO]; 

} 

@end 

我推它像這樣在App代表

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    // no story boards 
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 

    EAViewController *viewController = [[EAViewController alloc] init]; 
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; 
    navigationController.view.backgroundColor = [UIColor whiteColor]; 

    self.window.rootViewController = navigationController; 

    [self.window makeKeyAndVisible]; 
    // Override point for customization after application launch. 
    return YES; 
} 

的結果是,按鈕沒有正確的Y軸偏移。 如果我不使用導航控制器直接推視圖控制器,它可以工作。

問候, 揚

回答

0

我懷疑你的y偏移是關閉的相同數量的導航欄(48),因爲iOS的7現在進入全屏模式,即向上的導航欄下,所以這是正常的行爲。

相關問題