繁体   English   中英

iOS Autolayout如何在超级视图中扩展子视图

[英]iOS Autolayout how to stretch out subview in superview

在此处输入图片说明

如您在屏幕快照中所见,这里是灰色的UIView ,我将其用作容器。 在代码中,我分配了一个UINavigationController并将其视图作为子视图添加到灰色容器视图中。 UINavigationController具有RootViewController (您可以在左侧看到截止的表视图-这是我的UINavigationController的根视图控制器)。

我的问题是如何将所有方面都固定在superview范围内。 因为现在我可以看到RootViewController视图的一部分。

在情节提要中,我将所有约束设置为灰色容器视图,以及UINavigationController RootViewController视图。 如果我通常使用PushViewController而不是添加为子视图,则显示没有中断问题。

这是我在UIViewController中包含的代码,其中包含灰色容器视图:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];

    if (self)
    {
         KNCouponsViewController *couponsViewControllerByList = [KNInstantiateHelper instantiateViewControllerWithIdentifier:@"KNCouponsViewController"];

        self.theNavigationController = [[UINavigationController alloc] initWithRootViewController:couponsViewControllerByList];

    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.theContainerView addSubview:self.theNavigationController.view];
}

这是灰色容器视图的约束

在此处输入图片说明

这是已切断表的根视图控制器的视图的约束:

在此处输入图片说明

似乎一个简单的解决方案是将UINavigationController视图设置为与灰色容器具有相同的宽度和高度:

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect rect = self.theContainerView.frame;
    rect.origin.x = 0;
    rect.origin.y = 0;

    [self.theNavigationController.view setFrame:rect];

    [self.theContainerView addSubview:self.theNavigationController.view];
}

然后工作正常。 但是我认为,如果我们不只修改框架,它将起作用吗?

有两种方法。

  • 一种方法是在viewDidLayoutSubview方法中调用addSubView代码
  • 第二种方法是使用以下代码进行设置

    [self.theContainerView addSubview:self.theNavigationController.view]; [self.theNavigationController.view setFrame:self.theContainerView.frame];

注意:如果您使用第一种方法,请在以下位置添加代码

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{
[self.theContainerView addSubview:self.theNavigationController.view];
[self.containerView layoutIfNeeded];
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM