0

我有一个 homeview 控制器,我要在其中添加一个子视图。该子视图是 uiview 的子类。但 homeview 控制器不显示子视图。

这是我的代码。

#import "HomeViewController.h"
@interface HomeViewController : UIViewController {

DetailView *viewDetailFinal;
}
@property (nonatomic, retain) DetailView *viewDetailFinal;


@implementation HomeViewController

@synthesize viewDetailFinal;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
    viewDetailFinal = [[DetailView alloc] initWithFrame:CGRectMake(0, 0, 588, 899)];
}
return self;
}

- (void)viewDidLoad
{
   [self.view addSubview:viewDetailFinal];
}

#import "DetailView.h"

@interface DetailView : UIView{

}

-(void) loadView:(NSString *)str;


@implementation DetailView

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

    [self loadView:@"my test text"];
   }
   return self;
}

-(void) loadView:(NSString *)str {
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 150, 25)];
    [lbl setFont:[UIFont boldSystemFontOfSize:12.0]];
    [lbl setTextColor:[UIColor blackColor]];
    [lbl setTextAlignment:UITextAlignmentCenter];
    [lbl setBackgroundColor:[UIColor blueColor]];
    [lbl setText:str];
}

任何人都可以建议我错在哪里?任何帮助将不胜感激。

4

2 回答 2

1

在您实施该-(void) loadView:(NSString *)str方法时,您不会将标签添加到视图中:

-(void) loadView:(NSString *)str {
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 150, 25)];
    [lbl setFont:[UIFont boldSystemFontOfSize:12.0]];
    [lbl setTextColor:[UIColor blackColor]];
    [lbl setTextAlignment:UITextAlignmentCenter];
    [lbl setBackgroundColor:[UIColor blueColor]];
    [lbl setText:str];

    [self addSubView:lbl];
}
于 2012-07-04T10:39:45.747 回答
1

首先将标签添加到您的视图中,如下所示....

-(void) loadView:(NSString *)str {
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 150, 25)];
[lbl setFont:[UIFont boldSystemFontOfSize:12.0]];
[lbl setTextColor:[UIColor blackColor]];
[lbl setTextAlignment:UITextAlignmentCenter];
[lbl setBackgroundColor:[UIColor blueColor]];
[lbl setText:str];

[self addSubView:lbl];
}

然后在你看来你的控制器类的加载方法......

- (void)viewDidLoad
{
    viewDetailFinal  = [[DetailView  alloc] initWithFrame:CGRectMake(0.0,0.0,320.0,460.0)];
    viewDetailFinal.backgroundColor = [UIColor redColor]; //Just for your verification
    [self.view addSubview:viewDetailFinal];
}

这可能会帮助你

于 2012-07-04T11:21:40.103 回答