【问题标题】:UIView addSubview and the subview isn't displayedUIView addSubview 和子视图不显示
【发布时间】:2015-12-29 17:34:24
【问题描述】:
- (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

【问题讨论】:

    标签: ios uiview


    【解决方案1】:

    首先,您不需要在HeadViewController 类中定义view 插座。它自动继承自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类实现文件开头的隐藏接口定义中。

    【讨论】:

    • 我纠正你:headViewController.view 是 nil,如果它没有添加为子视图。需要交换 addsubview 并设置框架
    • 查看我关于 ARC 的更新。如果headViewController.viewnil,请仔细检查视图与 nib 文件中控制器的连接。 nil 是在这个方法内部(出口问题)还是在它完成之后(ARC 问题)?
    • 我更改了代码,就像你告诉我的那样,我定义了一个视图,因为我删除了默认视图。而且还没有headViewController.view...我很困惑。
    • NIB 文件中文件的所有者对象是否定义为HeadViewController 对象?你检查过插座连接吗?如果一切都正确配置,它必须工作。否则我不知道如何帮助你,对不起。 headViewController 值是非零值吗?
    • 您使用的 NIB 名称可能有问题?
    【解决方案2】:

    它看起来像一个错字 - 忘记了 .view 中的 i

    [查看 addSubview:headViewController.vew];

    【讨论】:

    • 这可能是正确的,但看起来 op 很久以前就已经解决了这个问题......
    【解决方案3】:

    语法中缺少i

    [查看 addSubview:headViewController.view];

    【讨论】:

    • 答案是 2 年前提供的。现在的目的是什么?
    猜你喜欢
    • 2015-09-17
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多