UIView addSubview并且不显示子视图

时间:2012-03-29 06:28:41

标签: ios uiview

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    HeadViewController *headViewController = [[HeadViewController alloc] initWithNibName:@"HeadViewController" bundle:nil];    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 120)];
    [view addSubview:headViewController.vew];
    [self.view addSubview:view];
}

HeadViewController.h:

@interface HeadViewController : UIViewController
{
    IBOutlet UIView *view;
}
@property (nonatomic, retain)IBOutlet UIView *view;
@end

我将视图连接到文件的所有者。

我无法看到headViewController.view

3 个答案:

答案 0 :(得分:15)

首先,您无需在view课程中定义HeadViewController插座。它自动从UIViewController超类继承。

然后,我建议您直接将HeadViewController的视图添加到当前视图中。例如

- (void)viewDidLoad
{
     [super viewDidLoad];
     // Do any additional setup after loading the view from its nib.
     HeadViewController *headViewController = [[HeadViewController alloc] initWithNibName:@"HeadViewController" bundle:nil];    
     headViewController.view.frame = CGRectMake(0, 0, 320, 120);
     [self.view addSubview:headViewController.view];
}

但是,如果您使用ARC(自动引用计数),headViewController方法可能会在viewDidLoad方法结束后释放- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. self.headViewController = [[HeadViewController alloc] initWithNibName:@"HeadViewController" bundle:nil]; headViewController.view.frame = CGRectMake(0, 0, 320, 120); [self.view addSubview:headViewController.view]; } 实例。将该实例分配给您当前正在显示的控制器中的局部变量很方便(并且我说这是必须的)。这样,您可以在以后需要时处理其视图的组件,实例将被保留,其他所有内容都将完美运行。你应该有类似的东西:

@interface MyController ()
    @property (nonatomic, strong) HeadViewController *headViewController;
@end

.m

在{{1}}类实现文件开头的隐藏接口定义中。

答案 1 :(得分:0)

这看起来像是一个错字 - 忘了我在.view

[查看addSubview:headViewController.vew];

答案 2 :(得分:0)

我在语法中缺少

[查看addSubview:headViewController.view];