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