【问题标题】:How to fill iOS Stack View (UIStackView) with an image as a background?如何用图像作为背景填充 iOS 堆栈视图(UIStackView)?
【发布时间】:2016-01-27 06:43:36
【问题描述】:

我想将堆栈视图背景设置为图像。例如,在 Android 中,如果我使用“线性布局”(相当于 UIStackView),我可以将背景图像设置为“线性布局”,而不管我添加什么内容(视图)。 我如何使用 XCode 做到这一点?

【问题讨论】:

  • UIStackViews 是不可渲染的对象。您不能将背景颜色或图像设置为 UIStackView。为此,您需要将 stackview 放在 UIView 或 UIImageView 中。

标签: ios xcode uistoryboard uistackview


【解决方案1】:

你不能这样做,UIStackView 是一个非绘图视图,这意味着 drawRect() 永远不会被调用。如果您想要背景图片,请考虑将堆栈视图放在 UIImageView 中。

【讨论】:

  • 感谢您的想法。我在 UIView 中成功添加了 UIStackView。但是,当我尝试在内部 UIStackView 中添加视图时,我遇到了约束错误。
【解决方案2】:

如上所述,您不能将图像背景添加到堆栈视图。

实现的方法是添加一个UIView,然后将一个ImageView和现有的stackview嵌套到刚刚添加的UIView中。此外,您需要对 imageview 应用相应的约束以适应整个背景 (0, 0 , 0 , 0)

大纲应如下所示:

【讨论】:

    【解决方案3】:

    如果你用代码编写 UIStackview 或许你可以试试下面~

    UIScrollView *scrollview = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [[scrollview layer] setContents:(__bridge id)[[UIImage imageNamed:@"your_background.jpg"] CGImage]];
    [[scrollview layer] setContentsGravity:kCAGravityResizeAspectFill];
    [self.view addSubview:scrollview];
    
    UIStackView *stackview = [[UIStackView alloc] init];
    [stackview setTranslatesAutoresizingMaskIntoConstraints:NO];
    [stackview setAxis:UILayoutConstraintAxisVertical];
    [stackview setDistribution:UIStackViewDistributionFill];
    [scrollview addSubview:stackview];
    
    NSDictionary *dic_vfl = NSDictionaryOfVariableBindings(stackview,scrollview);
    
    NSArray *array = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[stackview(scrollview)]|" options:0 metrics:nil views:dic_vfl];
    [scrollview addConstraints:array];
    array = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[stackview]|" options:0 metrics:nil views:dic_vfl];
    [scrollview addConstraints:array];
    
    //add view to stackview for test
    
    srand48(arc4random());
    
    for(int i=0;i<50;i++){
    
        UIColor *rc = [UIColor colorWithRed:drand48() green:drand48() blue:drand48() alpha:0.5];
    
        UIView *view_test = [[UIView alloc]init];
        [view_test setTranslatesAutoresizingMaskIntoConstraints:NO];
        [view_test setBackgroundColor:rc];
        [stackview addArrangedSubview:view_test];
    
        dic_vfl = NSDictionaryOfVariableBindings(view_test);
        array = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view_test]|" options:0 metrics:nil views:dic_vfl];
        [stackview addConstraints:array];
        array = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[view_test(50)]" options:0 metrics:nil views:dic_vfl];
        [stackview addConstraints:array];
    
    }
    

    希望这有用!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2016-02-12
      • 2019-01-28
      • 1970-01-01
      • 2011-12-26
      • 2018-10-02
      • 2018-09-26
      相关资源
      最近更新 更多