1

我想创建一个具有自动布局按钮的 UIViewController。(与 WWDC 2012 会话 202 相同)此视图控制器被推送到 UINavigationController 中。

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

问题是如何设置视图控制器主视图的尺寸,使其具有屏幕大小?

我的视图控制器如下所示:

@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 Delegate 中像这样推送它

- (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 偏移。如果我直接推送视图控制器而不使用导航控制器,它可以工作。

4

1 回答 1

0

我怀疑您的 y 偏移量与导航栏 (48) 的偏移量相同,因为 iOS 7 现在进入全屏状态,即在导航栏下方,所以这是正常行为。

于 2013-11-25T22:35:35.243 回答