【问题标题】:Custom child view does not fit parent自定义子视图不适合父视图
【发布时间】:2020-11-16 22:09:56
【问题描述】:

我在 XIB 中有一个与 viewController 链接的视图设置,XIB 中的所有视图都具有预期的布局。但是,某些视图必须在代码中初始化,因此我将它们添加为子视图,这样:

//Setup first custom view
FirstCustomView *firstCustomView = [[FirstCustomView alloc] initWithFrame: self.firstView.frame withDelegate:self];
 //where self.firstView is a UIView
[self.firstView addSubview: firstCustomView];

//Setup second custom view
SecondCustomView *secondCustomView = [[[NSBundle mainBundle] loadNibNamed:@"SecondCustomView" owner:nil options:nil] firstObject];
 //where self.secondView is a UIView
[self.secondView addSubview: secondCustomView];

正如您所见,有些视图是从 XIB 初始化的,有些是用框架初始化的。无论哪种方式,我都遇到了同样的问题,即子视图没有填充父视图。有什么建议吗?

【问题讨论】:

    标签: ios objective-c autolayout xib autoresize


    【解决方案1】:

    我用于这类东西的一些代码...

    // Given a parent view, embed a child view in it so that the child spans the full parent
    + ( void ) embed:( UIView * ) child
            into:( UIView * ) parent
    {
        [parent addSubview:child];
        
        [child.topAnchor    constraintEqualToAnchor:parent.topAnchor].active    = YES;
        [child.rightAnchor  constraintEqualToAnchor:parent.rightAnchor].active  = YES;
        [child.leftAnchor   constraintEqualToAnchor:parent.leftAnchor].active   = YES;
        [child.bottomAnchor constraintEqualToAnchor:parent.bottomAnchor].active = YES;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多