【问题标题】:Fit CustomView into SuperView with Autolayout使用 Autolayout 将 CustomView 适配到 SuperView
【发布时间】:2015-01-17 18:55:26
【问题描述】:

我正在尝试创建一个基于此tutorial 翻转的卡片视图。它创建一个 UIView 并添加卡片视图。

为此,我创建了一个自定义 UIView(使用 Xib),到目前为止它运行良好。我在 Storyboard 中为调用 addSubview 的视图添加了正确的约束。到目前为止,这是可行的,但是当我添加自定义 UIView 时,它指的是它在 xib 中的大小,而不是超级视图的大小。

如何添加必要的自动布局约束以使子视图适合其父视图?

谢谢!

附:我已经用 Objective-C 编写了它,但答案是 swift 还是 Objective-C 对我来说并不重要。

【问题讨论】:

    标签: ios objective-c swift autolayout


    【解决方案1】:

    不确定,有什么问题。我通过以下方式做了同样的事情:

    1) ProductItemView,UIView 的子类,并创建了具有 UIView 对象的 ProductItemView.xib。

    2) 在 .xib 中将 File 的所有者类设置为 ProductItemView,以便可以加载 .xib 和其他子视图的 UIView 对象并与 IBOutlet 链接。(见图)

    3) 在 init 方法(在我的例子中为 initWithFrame)方法中放入代码

        NSArray *nibViewArray = [[NSBundle mainBundle] loadNibNamed:@"ProductItemView" owner:self options:nil];
    
        if (nibViewArray.count) {
            UIView *nibView = [nibViewArray objectAtIndex:0];
            [self addSubview:nibView];
    
            nibView.translatesAutoresizingMaskIntoConstraints = NO;
    
            NSDictionary *viewDict = NSDictionaryOfVariableBindings(nibView);
            [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[nibView]-0-|" options:0 metrics:nil views:viewDict]];
    
            [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[nibView]-0-|" options:0  metrics:nil views:viewDict]];
    
        }
    

    最后创建 ProdutItemView 对象并使用框架或设置约束并将其添加到超级视图。如果您正在设置约束,请不要忘记将 translatesAutoresizingMaskIntoConstraints 属性设置为 NO。 希望对您有所帮助。

    【讨论】:

    • 我会接受这个答案,因为它更清楚一点,我必须做什么。对于翻转动画,在将其添加到我翻转的“StoryboardView”之后,我还必须为每个 FlipView(正面和背面)添加这些约束。此外,我必须在每次翻转时删除并添加这些约束(例如,显示前:添加前约束,删除后约束)。最后,我不得不将这些约束添加到 Storyboard View 和 CustomView。
    【解决方案2】:

    如果您想在代码中执行此操作。似乎对我来说效果更好,更有意义。

    // make sure myCustomView is added to the superview
    // and ignore the layout guides if the superview is not your view controller
    [myCustomView setTranslatesAutoresizingMaskIntoConstraints: NO];
    
    id topGuide = self.topLayoutGuide;
    id bottomGuide = self.bottomLayoutGuide;
    
    NSDictionary * viewsDictionary = NSDictionaryOfVariableBindings(myCustomView, topGuide, bottomGuide);
    
    [mySuperiew addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[myCustomView]|" options:0 metrics: 0 views:viewsDictionary]];
    
    [mySuperiew addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[topGuide][myCustomView][bottomGuide]|" options:0 metrics: 0 views:viewsDictionary]];
    

    【讨论】:

    • 这似乎部分起作用。我必须将它添加到我的“故事板视图”以适应自定义视图。此外,我必须将其添加到我的自定义视图中以适合其内容视图。当第一次这样做时,它工作正常,但在翻转两次(返回第一个视图)后,它会扭曲 customview.contentview 的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    相关资源
    最近更新 更多