【问题标题】:How to access properties from view after it loaded加载后如何从视图中访问属性
【发布时间】:2014-03-19 00:23:56
【问题描述】:

故事板:

约束:

结果:

我正在尝试了解自动布局以及如何在容器中使用它。

当我打开 Storyboard 时,我得到了一个为我制作的默认 ViewController。我在里面放了一个 View Container。然后我添加了一个松散的(未连接到任何东西)ViewController。我希望将新 ViewController 中的内容放入容器中。

所以添加的 ViewController 将被放入容器中,由三个标签组成,我正在使用自动布局。

单击故事板中容器视图控制器的黑条,我转到身份检查器并将自定义类设置为“ContainerViewController”。然后我将 Storyboard ID 设置为松散视图控制器的“ChildController”。

然后我在ContainerViewController.m 中覆盖viewDidLoad

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIViewController *child = [self.storyboard instantiateViewControllerWithIdentifier:@"ChildController"];
    [self addChildViewController:child];
    [self.view addSubview:child.view];

}

为什么放在容器中时自动布局的约束不起作用?我希望他们会这样做,所以我可以更进一步地了解 UIPageViewController。

编辑:

所以它似乎是帧大小。在将其添加为子视图之前,我需要做这样的事情:

child.view.frame = CGRectMake(0, 0, 265, 370);

现在我在ViewController.h 中为容器创建了一个出口。

@property (weak, nonatomic) IBOutlet UIView *container;

但是.. 从 ContainerViewController 中,当它尚未设置时,我如何询问呈现该属性的视图控制器(ViewController)?

ViewController *parent = (ViewController*)self.presentingViewController;
UIView *container = parent.container;

NSLog(@"ParentView Container Width: %f, Height: %f", container.frame.size.width, container.frame.size.height);

它只是给了我零宽度和高度,因为视图还没有加载。稍后当它加载时,我得到了实际值..

NSLog(@"View Controller Container. Width: %f, Height: %f", self.container.frame.size.width, self.container.frame.size.height);

问题:如何在presentingViewController 准备好/加载后访问它们的属性?

【问题讨论】:

    标签: ios iphone objective-c


    【解决方案1】:

    当添加一个子视图控制器时,你应该像这样设置它的视图框架

    UIViewController *child = [self.storyboard instantiateViewControllerWithIdentifier:@"ChildController"];
    [self addChildViewController:child];
    [self.view addSubview:child.view];
    
    //set the view frame
    child.view.frame = self.view.bounds;
    

    因此子视图控制器将调整其视图框架的大小,布局约束将完成他们的功课;)

    编辑

    将代码放入-(void)viewDidLayoutSubviews,如下所示:

    -(void)viewDidLayoutSubviews{
        [super viewDidLayoutSubviews];
        UIViewController *child = [self.storyboard instantiateViewControllerWithIdentifier:@"ChildController"];
        [self addChildViewController:child];
        [self.view addSubview:child.view];
    
        //set the view frame
        child.view.frame = self.view.bounds;
    }
    

    【讨论】:

    • NSLog(@"Bounds %f", self.view.bounds.size.height) 是480。但是容器比那个小,看Storyboard的图像,首先是ViewController。
    • 我的猜测是因为在 veiwDidLoad 中还没有设置边界。尝试改用 viewWillLayoutSubviews。
    • 把上面的代码放在-(void)viewDidLayoutSubviews而不是-(void)viewDidLoad
    【解决方案2】:

    只需尝试在viewWillLayoutSubviews 中为视图控制器设置框架

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多