AutoLayout without usage of Storyboards or Interface Builder

对着背影说爱祢 提交于 2019-12-02 08:28:48

问题


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 my Info.plist
  • manually setup self.window in AppDelegate.m and added UINavigationController with MainMainController as rootViewController

As mentioned, my main issue is that updateViewConstraints does not get called on MainViewController but the UI elements are all displayed with the frames 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!