简体   繁体   English

以编程方式在 UIStackView 中添加视图

[英]Add views in UIStackView programmatically

I'm trying to add views in UIStackView programmatically.我正在尝试以编程方式在 UIStackView 中添加视图。 For now My code is:现在我的代码是:

UIView *view1 = [[UIView alloc]init];
view1.backgroundColor = [UIColor blackColor];
[view1 setFrame:CGRectMake(0, 0, 100, 100)];

UIView *view2 =  [[UIView alloc]init];
view2.backgroundColor = [UIColor greenColor];
[view2 setFrame:CGRectMake(0, 100, 100, 100)];

[self.stack1 addArrangedSubview:view1];
[self.stack1 addArrangedSubview:view2];

When i deploy the app, there is only 1 view and it is with black colour.(view1 get the parameters for view2 too)当我部署应用程序时,只有 1 个视图,它是黑色的。(view1 也获取 view2 的参数)

Stack views use intrinsic content size, so use layout constraints to define the dimensions of the views.堆栈视图使用内在内容大小,因此使用布局约束来定义视图的尺寸。

There is an easy way to add constraints quickly (example):有一种简单的方法可以快速添加约束(示例):

[view1.heightAnchor constraintEqualToConstant:100].active = true;

Complete Code:完整代码:

- (void) setup {

    //View 1
    UIView *view1 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor blueColor];
    [view1.heightAnchor constraintEqualToConstant:100].active = true;
    [view1.widthAnchor constraintEqualToConstant:120].active = true;


    //View 2
    UIView *view2 = [[UIView alloc] init];
    view2.backgroundColor = [UIColor greenColor];
    [view2.heightAnchor constraintEqualToConstant:100].active = true;
    [view2.widthAnchor constraintEqualToConstant:70].active = true;

    //View 3
    UIView *view3 = [[UIView alloc] init];
    view3.backgroundColor = [UIColor magentaColor];
    [view3.heightAnchor constraintEqualToConstant:100].active = true;
    [view3.widthAnchor constraintEqualToConstant:180].active = true;

    //Stack View
    UIStackView *stackView = [[UIStackView alloc] init];

    stackView.axis = UILayoutConstraintAxisVertical;
    stackView.distribution = UIStackViewDistributionEqualSpacing;
    stackView.alignment = UIStackViewAlignmentCenter;
    stackView.spacing = 30;


    [stackView addArrangedSubview:view1];
    [stackView addArrangedSubview:view2];
    [stackView addArrangedSubview:view3];

    stackView.translatesAutoresizingMaskIntoConstraints = false;
    [self.view addSubview:stackView];


    //Layout for Stack View
    [stackView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = true;
    [stackView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = true;
}

Note: This was tested on iOS 9注意:这是在 iOS 9 上测试的

UIStackView 等间距(居中)

Swift 5.0斯威夫特 5.0

//Image View
let imageView = UIImageView()
imageView.backgroundColor = UIColor.blue
imageView.heightAnchor.constraint(equalToConstant: 120.0).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 120.0).isActive = true
imageView.image = UIImage(named: "buttonFollowCheckGreen")

//Text Label
let textLabel = UILabel()
textLabel.backgroundColor = UIColor.yellow
textLabel.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true
textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel.text  = "Hi World"
textLabel.textAlignment = .center

//Stack View
let stackView   = UIStackView()
stackView.axis  = NSLayoutConstraint.Axis.vertical
stackView.distribution  = UIStackView.Distribution.equalSpacing
stackView.alignment = UIStackView.Alignment.center
stackView.spacing   = 16.0

stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(textLabel)
stackView.translatesAutoresizingMaskIntoConstraints = false

self.view.addSubview(stackView)

//Constraints
stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

Based on @user1046037 answer.基于@user1046037 的回答。

In Swift 4.2在 Swift 4.2 中

let redView = UIView()
redView.backgroundColor = .red

let blueView = UIView()
blueView.backgroundColor = .blue

let stackView = UIStackView(arrangedSubviews: [redView, blueView])
stackView.axis = .vertical
stackView.distribution = .fillEqually

view.addSubview(stackView)

// stackView.frame = CGRect(x: 0, y: 0, width: 200, height: 200)

// autolayout constraint
stackView.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
    stackView.topAnchor.constraint(equalTo: view.topAnchor),
    stackView.leftAnchor.constraint(equalTo: view.leftAnchor),
    stackView.rightAnchor.constraint(equalTo: view.rightAnchor),
    stackView.heightAnchor.constraint(equalToConstant: 200)
])

UIStackView uses constraints internally to position its arranged subviews. UIStackView内部使用约束来定位其排列的子视图。 Exactly what constraints are created depends on how the stack view itself is configured.究竟创建什么约束取决于堆栈视图本身的配置方式。 By default, a stack view will create constraints that lay out its arranged subviews in a horizontal line, pinning the leading and trailing views to its own leading and trailing edges.默认情况下,堆栈视图将创建约束,将其排列的子视图布置在水平线上,将前导和后置视图固定到其自己的前缘和后缘。 So your code would produce a layout that looks like this:因此,您的代码将生成如下所示的布局:

|[view1][view2]|

The space that is allocated to each subview is determined by a number of factors including the subview's intrinsic content size and it's compression resistance and content hugging priorities.分配给每个子视图的空间由许多因素决定,包括子视图的内在内容大小及其抗压缩性和内容拥抱优先级。 By default, UIView instances don't define an intrinsic content size.默认情况下, UIView实例不定义内在内容大小。 This is something that is generally provided by a subclass, such as UILabel or UIButton .这是通常由子类提供的东西,例如UILabelUIButton

Since the content compression resistance and content hugging priorities of two new UIView instances will be the same, and neither view provides an intrinsic content size, the layout engine must make its best guess as to what size should be allocated to each view.由于两个新UIView实例的内容压缩阻力和内容拥抱优先级将相同,并且两个视图都没有提供固有的内容大小,因此布局引擎必须对应该为每个视图分配什么大小做出最佳猜测。 In your case, it is assigning the first view 100% of the available space, and nothing to the second view.在您的情况下,它为第一个视图分配 100% 的可用空间,而没有分配给第二个视图。

If you modify your code to use UILabel instances instead, you will get better results:如果您修改代码以使用UILabel实例,您将获得更好的结果:

UILabel *label1 = [UILabel new];
label1.text = @"Label 1";
label1.backgroundColor = [UIColor blueColor];

UILabel *label2 = [UILabel new];
label2.text = @"Label 2";
label2.backgroundColor = [UIColor greenColor];

[self.stack1 addArrangedSubview:label1];
[self.stack1 addArrangedSubview:label2];

Note that it is not necessary to explictly create any constraints yourself.请注意,没有必要自己明确地创建任何约束。 This is the main benefit of using UIStackView - it hides the (often ugly) details of constraint management from the developer.这是使用UIStackView的主要好处 - 它向开发人员隐藏了约束管理的(通常是丑陋的)细节。

You have to set you distribution type.您必须设置分发类型。 In your code, juste add:在您的代码中,添加:

self.stack1.distribution = UIStackViewDistributionFillEqually;

Or you can set the distribution directly in your interface builder.或者您可以直接在界面构建器中设置分发。 For example:例如:

在此处输入图片说明

Hope that helps ;) Lapinou.希望有所帮助 ;) Lapinou。

Following two lines fixed my issue以下两行解决了我的问题

view.heightAnchor.constraintEqualToConstant(50).active = true;
view.widthAnchor.constraintEqualToConstant(350).active = true;

Swift version -斯威夫特版——

var DynamicView=UIView(frame: CGRectMake(100, 200, 100, 100))
DynamicView.backgroundColor=UIColor.greenColor()
DynamicView.layer.cornerRadius=25
DynamicView.layer.borderWidth=2
self.view.addSubview(DynamicView)
DynamicView.heightAnchor.constraintEqualToConstant(50).active = true;
DynamicView.widthAnchor.constraintEqualToConstant(350).active = true;

var DynamicView2=UIView(frame: CGRectMake(100, 310, 100, 100))
DynamicView2.backgroundColor=UIColor.greenColor()
DynamicView2.layer.cornerRadius=25
DynamicView2.layer.borderWidth=2
self.view.addSubview(DynamicView2)
DynamicView2.heightAnchor.constraintEqualToConstant(50).active = true;
DynamicView2.widthAnchor.constraintEqualToConstant(350).active = true;

var DynamicView3:UIView=UIView(frame: CGRectMake(10, 420, 355, 100))
DynamicView3.backgroundColor=UIColor.greenColor()
DynamicView3.layer.cornerRadius=25
DynamicView3.layer.borderWidth=2
self.view.addSubview(DynamicView3)

let yourLabel:UILabel = UILabel(frame: CGRectMake(110, 10, 200, 20))
yourLabel.textColor = UIColor.whiteColor()
//yourLabel.backgroundColor = UIColor.blackColor()
yourLabel.text = "mylabel text"
DynamicView3.addSubview(yourLabel)
DynamicView3.heightAnchor.constraintEqualToConstant(50).active = true;
DynamicView3.widthAnchor.constraintEqualToConstant(350).active = true;

let stackView   = UIStackView()
stackView.axis  = UILayoutConstraintAxis.Vertical
stackView.distribution  = UIStackViewDistribution.EqualSpacing
stackView.alignment = UIStackViewAlignment.Center
stackView.spacing   = 30

stackView.addArrangedSubview(DynamicView)
stackView.addArrangedSubview(DynamicView2)
stackView.addArrangedSubview(DynamicView3)

stackView.translatesAutoresizingMaskIntoConstraints = false;

self.view.addSubview(stackView)

//Constraints
stackView.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor).active = true
stackView.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor).active = true

For the accepted answer when you try to hide any view inside stack view, the constraint works not correct.对于当您尝试隐藏堆栈视图内的任何视图时接受的答案,约束工作不正确。

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x618000086e50 UIView:0x7fc11c4051c0.height == 120   (active)>",
    "<NSLayoutConstraint:0x610000084fb0 'UISV-hiding' UIView:0x7fc11c4051c0.height == 0   (active)>"
)

Reason is when hide the view in stackView it will set the height to 0 to animate it.原因是当在stackView隐藏view ,它会将高度设置为 0 以对其进行动画处理。

Solution change the constraint priority as below.解决方案更改约束priority如下。

import UIKit

class ViewController: UIViewController {

    let stackView = UIStackView()
    let a = UIView()
    let b = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        a.backgroundColor = UIColor.red
        a.widthAnchor.constraint(equalToConstant: 200).isActive = true
        let aHeight = a.heightAnchor.constraint(equalToConstant: 120)
        aHeight.isActive = true
        aHeight.priority = 999

        let bHeight = b.heightAnchor.constraint(equalToConstant: 120)
        bHeight.isActive = true
        bHeight.priority = 999
        b.backgroundColor = UIColor.green
        b.widthAnchor.constraint(equalToConstant: 200).isActive = true

        view.addSubview(stackView)
        stackView.backgroundColor = UIColor.blue
        stackView.addArrangedSubview(a)
        stackView.addArrangedSubview(b)
        stackView.axis = .vertical
        stackView.distribution = .equalSpacing
        stackView.translatesAutoresizingMaskIntoConstraints = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // Just add a button in xib file or storyboard and add connect this action.
    @IBAction func test(_ sender: Any) {
        a.isHidden = !a.isHidden
    }

}
    //Image View
    let imageView               = UIImageView()
    imageView.backgroundColor   = UIColor.blueColor()
    imageView.heightAnchor.constraintEqualToConstant(120.0).active = true
    imageView.widthAnchor.constraintEqualToConstant(120.0).active = true
    imageView.image = UIImage(named: "buttonFollowCheckGreen")

    //Text Label
    let textLabel               = UILabel()
    textLabel.backgroundColor   = UIColor.greenColor()
    textLabel.widthAnchor.constraintEqualToConstant(self.view.frame.width).active = true
    textLabel.heightAnchor.constraintEqualToConstant(20.0).active = true
    textLabel.text  = "Hi World"
    textLabel.textAlignment = .Center


    //Third View
    let thirdView               = UIImageView()
    thirdView.backgroundColor   = UIColor.magentaColor()
    thirdView.heightAnchor.constraintEqualToConstant(120.0).active = true
    thirdView.widthAnchor.constraintEqualToConstant(120.0).active = true
    thirdView.image = UIImage(named: "buttonFollowMagenta")


    //Stack View
    let stackView   = UIStackView()
    stackView.axis  = UILayoutConstraintAxis.Vertical
    stackView.distribution  = UIStackViewDistribution.EqualSpacing
    stackView.alignment = UIStackViewAlignment.Center
    stackView.spacing   = 16.0

    stackView.addArrangedSubview(imageView)
    stackView.addArrangedSubview(textLabel)
    stackView.addArrangedSubview(thirdView)
    stackView.translatesAutoresizingMaskIntoConstraints = false;

    self.view.addSubview(stackView)

    //Constraints
    stackView.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor).active = true
    stackView.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor).active = true

Improved on the answer by @Oleg Popov改进了@Oleg Popov 的回答

In my case the thing that was messing with I would expect was that I was missing this line:在我的情况下,我期望的事情是我错过了这一行:

stackView.translatesAutoresizingMaskIntoConstraints = false;

After that no need to set constraints to my arranged subviews whatsoever, the stackview is taking care of that.之后,无需为我安排的子视图设置约束,堆栈视图会处理这些。

Swift 5 version of Oleg Popov's answer , which is based on user1046037's answer Swift 5版本的Oleg Popov's answer ,这是基于user1046037's answer

//Image View
let imageView = UIImageView()
imageView.backgroundColor = UIColor.blue
imageView.heightAnchor.constraint(equalToConstant: 120.0).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 120.0).isActive = true
imageView.image = UIImage(named: "buttonFollowCheckGreen")

//Text Label
let textLabel = UILabel()
textLabel.backgroundColor = UIColor.yellow
textLabel.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true
textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel.text  = "Hi World"
textLabel.textAlignment = .center

//Stack View
let stackView   = UIStackView()
stackView.axis  = NSLayoutConstraint.Axis.vertical
stackView.distribution  = UIStackView.Distribution.equalSpacing
stackView.alignment = UIStackView.Alignment.center
stackView.spacing   = 16.0

stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(textLabel)
stackView.translatesAutoresizingMaskIntoConstraints = false

self.view.addSubview(stackView)

//Constraints
stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

If you have want to add UIView at specific position, use this如果您想在特定的 position 添加 UIView,请使用此

yourStackView.insertArrangedSubview(yourView, at: index)

I just came across very similar problem.我刚刚遇到了非常相似的问题。 Just like mentioned before the stack view's dimensions depend one intrinsic content size of the arranged subviews.就像之前提到的,堆栈视图的尺寸取决于排列子视图的一个内在内容大小。 Here is my solution in Swift 2.x and following view structure:这是我在 Swift 2.x 中的解决方案和以下视图结构:

view - UIView视图 - UIView

customView - CustomView:UIView自定义视图 - 自定义视图:UIView

stackView - UISTackView堆栈视图 - UIStackView

arranged subviews - custom UIView subclasses排列的子视图 - 自定义 UIView 子类

    //: [Previous](@previous)

import Foundation
import UIKit
import XCPlayground

/**Container for stack view*/
class CustomView:UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }


    init(){
        super.init(frame: CGRectZero)

    }

}

/**Custom Subclass*/
class CustomDrawing:UIView{
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()

    }

    func setup(){
       // self.backgroundColor = UIColor.clearColor()
        print("setup \(frame)")
    }

    override func drawRect(rect: CGRect) {
        let ctx = UIGraphicsGetCurrentContext()
        CGContextMoveToPoint(ctx, 0, 0)
        CGContextAddLineToPoint(ctx, CGRectGetWidth(bounds), CGRectGetHeight(bounds))
        CGContextStrokePath(ctx)

        print("DrawRect")

    }
}



//: [Next](@next)
let stackView = UIStackView()
stackView.distribution = .FillProportionally
stackView.alignment = .Center
stackView.axis = .Horizontal
stackView.spacing = 10


//container view
let view = UIView(frame: CGRectMake(0,0,320,640))
view.backgroundColor = UIColor.darkGrayColor()
//now custom view

let customView = CustomView()

view.addSubview(customView)

customView.translatesAutoresizingMaskIntoConstraints = false
customView.widthAnchor.constraintEqualToConstant(220).active = true
customView.heightAnchor.constraintEqualToConstant(60).active = true
customView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
customView.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor).active = true
customView.backgroundColor = UIColor.lightGrayColor()

//add a stack view
customView.addSubview(stackView)
stackView.centerXAnchor.constraintEqualToAnchor(customView.centerXAnchor).active = true
stackView.centerYAnchor.constraintEqualToAnchor(customView.centerYAnchor).active = true
stackView.translatesAutoresizingMaskIntoConstraints = false


let c1 = CustomDrawing()
c1.translatesAutoresizingMaskIntoConstraints = false
c1.backgroundColor = UIColor.redColor()
c1.widthAnchor.constraintEqualToConstant(30).active = true
c1.heightAnchor.constraintEqualToConstant(30).active = true

let c2 = CustomDrawing()
c2.translatesAutoresizingMaskIntoConstraints = false
c2.backgroundColor = UIColor.blueColor()
c2.widthAnchor.constraintEqualToConstant(30).active = true
c2.heightAnchor.constraintEqualToConstant(30).active = true


stackView.addArrangedSubview(c1)
stackView.addArrangedSubview(c2)


XCPlaygroundPage.currentPage.liveView = view

If you have many UIView s to add, you can use the following extension where you pass an array of UIView s where it will add them into the UIStackView by order如果您有许多UIView要添加,您可以使用以下扩展,在其中传递一组UIView ,它将按顺序将它们添加到UIStackView

extension UIStackView {
    func addArrangedSubviews(_ subviews: [UIView]) {
        subviews.forEach{ self.addArrangedSubview($0) }
    }
}

Instead of coding all the constrains you could use a subclass that handles .intrinsicContentSize of UIView class in a simpler way.您可以使用以更简单的方式处理UIView类的.intrinsicContentSize的子类,而不是对所有约束进行编码。 This solution improves also Interface Builder a little in a way to support with " intrinsicWidth " and " intrinsicHeight " of views.该解决方案还对Interface Builder 进行了一些改进,以支持视图的“ intrinsicWidth ”和“ intrinsicHeight ”。 While you could extend UIView's and have those properties available on all UIViews in IB its cleaner to subclass.虽然您可以扩展 UIView 并在IB 中的所有 UIViews 上使用这些属性,但它可以更清晰地进行子类化。

// IntrinsicView.h
@import UIKit

IB_DESIGNABLE
@interface IntrinsicView : UIView
-(instancetype)initWithFrame:(CGRect)rect;
@property IBInspectable CGSize intrinsic;
@end
// IntrinsicView.m
#import "IntrinsicView.h"

@implementation IntrinsicView {
    CGSize _intrinsic;
}
- (instancetype)initWithFrame:(CGRect)frame {
    _intrinsic = frame.size;
    if ( !(self = [super initWithFrame:frame]) ) return nil;
    // your stuff here..
    return self;
}
-(CGSize)intrinsicContentSize {
    return _intrinsic;
}
-(void)prepareForInterfaceBuilder {
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, _intrinsic.width,_intrinsic.height);
}
@end

Which means you can just allocate those IntrinsicView's and the self.frame.size is taken as intrinsicContentSize .这意味着您可以只分配那些 IntrinsicView 并且self.frame.size被视为intrinsicContentSize That way it does not disturb the normal layout and you dont need to set constraint relations that don't even apply in full with UIStackViews这样它就不会干扰正常的布局,并且您不需要设置甚至不完全适用于UIStackViews约束关系

#import "IntrinsicView.h"

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIStackView *column = [[UIStackView alloc] initWithFrame:self.view.frame];
    column.spacing = 2;
    column.alignment = UIStackViewAlignmentFill;
    column.axis = UILayoutConstraintAxisVertical; //Up-Down
    column.distribution = UIStackViewDistributionFillEqually;
    
    for (int row=0; row<5; row++) {
        //..frame:(CGRect) defines here proportions and
        //relation to axis of StackView
        IntrinsicView *intrinsicView = [[IntrinsicView alloc] initWithFrame:CGRectMake(0, 0, 30.0, 30.0)];
        
        [column addArrangedSubview:intrinsicView];
    }
    [self.view addSubview:column];
}

now you can go crazy with UIStackView's现在你可以为 UIStackView 疯狂了在此处输入图片说明

or in swift + encoding, decoding, IB support, Objective-C supportswift + 编码、解码、IB 支持、Objective-C 支持

@IBDesignable @objc class IntrinsicView : UIView {
    @IBInspectable var intrinsic : CGSize
    @objc override init(frame: CGRect) {
        intrinsic = frame.size
        super.init(frame: frame)
    }
    required init?(coder: NSCoder) {
        intrinsic = coder.decodeCGSize(forKey: "intrinsic")
        super.init(coder: coder)
    }
    override func encode(with coder: NSCoder) {
        coder.encode(intrinsic, forKey: "intrinsic")
        super.encode(with: coder)
    }
    override var intrinsicContentSize: CGSize {
        return intrinsic
    }
    override func prepareForInterfaceBuilder() {
        frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: intrinsic.width, height: intrinsic.height)
    }
}

It is really not recommended to set a height constraint... If you can, never, never, never set a height!真的不建议设置高度约束...如果可以,永远,永远,永远不要设置高度! You need to check all the constraints of the views inside your UIStackView and be sure that there is constraints for bottom, top, leading and trailing.您需要检查 UIStackView 中视图的所有约束,并确保底部、顶部、前导和尾随有约束。 Someone said to me: it is like a guy pushing on walls.有人对我说:这就像一个人在推墙。 If he don't push on 4 sides, one of the wall will fall on him.如果他不推 4 边,墙之一会倒在他身上。

func configureHorizontalView(){
    containerView.addSubview(horizontalStackView)
    _ = horizontalStackView.anchor(top: secondCurrencyTextField.bottomAnchor, 
                                   left: containerView.leftAnchor, 
                                   bottom: nil, 
                                   right: containerView.rightAnchor, 
                                   topConstant: 40, 
                                   leftConstant: 30, 
                                   bottomConstant: 0, 
                                   rightConstant: 30, 
                                   widthConstant: 0, 
                                   heightConstant: 65)
}

func configureFirstDropDownlabel(){
    //add a view to stackView with addArrangedSubview() 
    horizontalStackView.addArrangedSubview(firstDropDownlabel)
    _ = firstDropDownlabel.anchor(top: horizontalStackView.bottomAnchor, 
                                  left: horizontalStackView.leftAnchor, 
                                  bottom: nil, right: nil, 
                                  topConstant: 40, 
                                  leftConstant: 30, 
                                  bottomConstant: 0, 
                                  rightConstant: 0, 
                                  widthConstant: 0, 
                                  heightConstant: 0)
    firstDropDownlabel.widthAnchor.constraint(equalToConstant: 130).isActive = true
    firstDropDownlabel.heightAnchor.constraint(equalToConstant: 65).isActive = true
}

Try below code,试试下面的代码,

UIView *view1 = [[UIView alloc]init];
view1.backgroundColor = [UIColor blackColor];
[view1 setFrame:CGRectMake(0, 0, 50, 50)];

UIView *view2 =  [[UIView alloc]init];
view2.backgroundColor = [UIColor greenColor];
[view2 setFrame:CGRectMake(0, 100, 100, 100)];

NSArray *subView = [NSArray arrayWithObjects:view1,view2, nil];

[self.stack1 initWithArrangedSubviews:subView];

Hope it works.希望它有效。 Please let me know if you need anymore clarification.如果您需要更多说明,请告诉我。

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

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