无法在ipad中添加子视图

时间:2012-07-04 10:29:15

标签: iphone ios ipad uiview uiviewcontroller

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

这是我的代码。

#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];
}

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

2 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分: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];
}

然后在您的视图中执行Controller类的加载方法...

- (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];
}

这可能会对你有所帮助