问题
I am building an app where I want to completely avoid using Storyboard and Interface Builder in general, so all UI should be specified in code. I am using PureLayout, a nice API for configuring AutoLayout
constraints.
However, my issue is that it seems like AutoLayout
is disabled when not using Interface Builder. updateViewConstraints
, the method where I put the layout according to the recommendation given by the PureLayout
author, is not called at all.
Just to give a bit more info about my setup:
- deleted
Main.storyboard
and removed the entry from myInfo.plist
- manually setup
self.window
inAppDelegate.m
and addedUINavigationController
withMainMainController
asrootViewController
As mentioned, my main issue is that updateViewConstraints
does not get called on MainViewController
but the UI elements are all displayed with the frame
s that I passed to them during initilization.
Note: It seems to me like I just need to enable some flag somewhere to mimic the checkbox from Interface Builder with which you can indicate whether you want to use AutoLayout
.
MainViewController.m
@interface MainViewController ()
@property (nonatomic, strong) UIButton *startButton;
@property (nonatomic, assign) BOOL didSetupConstraints;
@end
@implementation MainViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view addSubview:self.startButton];
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
}
- (UIButton *)startButton
{
if (!_startButton) {
UIButton *startButton = [UIButton buttonWithType:UIButtonTypeSystem];
CGRect startButtonFrame = CGRectMake(75.0, 75.0, 250.0, 44.0);
startButton.frame = startButtonFrame;
[startButton setTitle:@"Start" forState:UIControlStateNormal];
[startButton setTranslatesAutoresizingMaskIntoConstraints:NO];
_startButton = startButton;
}
return _startButton;
}
- (void)updateViewConstraints
{
NSLog(@"Update view contraints");
if (!self.didSetupConstraints) {
[self.startButton autoCenterInSuperview];
self.didSetupConstraints = YES;
}
[super updateViewConstraints];
}
@end
来源:https://stackoverflow.com/questions/36173367/autolayout-without-usage-of-storyboards-or-interface-builder