试图在没有NIB的情况下让UILabel显示在视图中

时间:2009-06-19 20:15:17

标签: iphone

我是iPhone编程的新手,我正在尝试制作一个没有NIB的简单程序。我已经完成了一些NIB教程,但我想以编程方式尝试一些事情。

我的代码加载没有错误,使状态栏变黑,并使背景变白。但是,我认为我之后没有正确加载我的视图标签。我认为我做的事情从根本上说是错误的,所以如果你能指出我正确的方向,我会很感激。我想如果我能得到标签,我会得到一些理解。这是我的代码:

//helloUAppDelegate.h
#import <UIKit/UIKit.h>
#import "LocalViewController.h"

@interface helloUAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    LocalViewController *localViewController;
}

@property (nonatomic, retain) UIWindow *window;
@property (nonatomic, retain) LocalViewController *localViewController;

@end


//helloUApDelegate.m
#import "helloUAppDelegate.h"

@implementation helloUAppDelegate

@synthesize window, localViewController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {   
    application.statusBarStyle = UIStatusBarStyleBlackOpaque;
    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    if (!window) {
        [self release];
        return;
    }
    window.backgroundColor = [UIColor whiteColor];

    localViewController = [[LocalViewController alloc] init];

    [window addSubview:localViewController.view];

    // Override point for customization after application launch
    [window makeKeyAndVisible];
}


//LocalViewController.h
#import <UIKit/UIKit.h>

@interface LocalViewController : UIViewController {
    UILabel *myLabel;   
}

@property (nonatomic, retain) UILabel *myLabel;

@end


//LocalViewController.m
#import "LocalViewController.h"

@implementation LocalViewController

@synthesize myLabel;

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
    self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];      
    self.myLabel.text = @"Lorem...";
    self.myLabel.textColor = [UIColor redColor];
}

- (void)dealloc {
    [super dealloc];
    [myLabel release];
}

1 个答案:

答案 0 :(得分:3)

将您的标签添加到LocalViewController的视图中:

- (void)loadView {
    [super loadView];
    self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];      
    self.myLabel.text = @"Lorem...";
    self.myLabel.textColor = [UIColor redColor];
    [self addSubview:self.myLabel];
    [self.myLabel release];     // since it's retained after being added to the view
}
相关问题