如何用图像作为背景填充 iOS 堆栈视图(UIStackView)?

Posted

技术标签:

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

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

【问题讨论】:

UIStackViews 是不可渲染的对象。您不能将背景颜色或图像设置为 UIStackView。为此,您需要将 stackview 放在 UIView 或 UIImageView 中。 【参考方案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];


希望这有用!!

【讨论】:

以上是关于如何用图像作为背景填充 iOS 堆栈视图(UIStackView)?的主要内容,如果未能解决你的问题,请参考以下文章

在JavaFX中仅显示填充了图像的百分比

旋转QImage时如何用透明背景填充空白?

用两个图像视图填充横向模式的宽度

如何用渐变色填充部分背景?

iOS - 在堆栈视图中拉伸的图像

如何用图案填充图像