0

プログラムで作成された 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.mの実装のサブクラスです。UIViewController

- (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 メソッドは呼び出されません。私は何を間違っていますか?

ありがとう

4

1 に答える 1

0
- (void)loadView; 

UIView のメソッドではなく、UIViewController クラスのメソッドです。

そのため、すでに背景色を設定している init メソッド内でサブビューをセットアップする必要があります。

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        // Initialization code
    }
    return self;
}
于 2014-09-03T11:30:18.267 に答える