清洁以编程方式实现UI

时间:2014-09-03 11:02:26

标签: objective-c ios7 uiviewcontroller subviews programmatically-created

我正在尝试以编程方式创建UI的干净实现。

我从我的AppDelegate.m

开始
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];


    MainViewController *mainVC = [[MainViewController alloc] init];

    UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:mainVC];

    self.window.rootViewController = navC;

    [self.window makeKeyAndVisible];
    return YES;

}

然后MainViewController.mUIViewController的子类实现以下内容:

- (void)loadView {

    CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
    MenuView *contentView = [[MenuView alloc] initWithFrame:applicationFrame];
    self.view = contentView;

}

UIView中的自定义MenuView.m实现了以下

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        NSLog(@"init got called");
        NSLog(@"frame size %f %f", self.frame.size.width, self.frame.size.height);
        self.backgroundColor = [UIColor greenColor];
    }
    return self;
}

 ...

- (void)loadView {

    NSLog(@"loadView got called");

    UIButton *newButton = [[UIButton alloc] init];
    newButton.titleLabel.text = @"New Button";
    newButton.backgroundColor = [UIColor blueColor];
    [self addSubview:newButton];

    NSDictionary *views = NSDictionaryOfVariableBindings(newButton);

    [newButton setTranslatesAutoresizingMaskIntoConstraints:NO];

    NSDictionary *metrics = @{@"buttonWidth": @(150), @"buttonHeight": @(150)};

    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(100)-[newButton(buttonWidth)]"
                                                                 options:0 metrics:metrics views:views]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[newButton(buttonHeight)]-(100)-|"
                                                                 options:0 metrics:metrics views:views]];

}

当我运行时,模拟器显示绿屏 - 但没有按钮。 init方法中的NSLog会触发并显示320 x 548的帧大小,但不会调用loadView方法。 我做错了什么?

由于

1 个答案:

答案 0 :(得分:0)

- (void)loadView; 

是UIViewController类的方法,而不是UIView的。

因此,您需要在已设置背景颜色的init方法中设置其子视图。

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        // Initialization code
    }
    return self;
}