代码之家  ›  专栏  ›  技术社区  ›  iProgram

Swift,如何动态添加X个带约束的视图

  •  -1
  • iProgram  · 技术社区  · 7 年前

    我正在开发一个swift应用程序,可以在屏幕上显示10个项目。如果我想在一个不会改变大小的屏幕上这样做,即用户不改变方向或者iPad用户不使用分屏,我可以通过这样做来检测宽度 let size = bounds.width/19 .

    问题是,因为屏幕大小是动态的,所以我需要做它的限制。我不想使用UICollectionView,因为它太重了,如果可能的话,我也不想使用UIStackView,因为我认为它不支持圆所需要的纵横比。我正在尝试使用UIView。

    编辑: 这就是我想要他们的样子。这将是大约50高,其他信息将在下面。

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  2
  •   iProgram    7 年前

    UIStackView 希望

    let sv = UIStackView()
    sv.spacing = 10
    // this means each arranged subview will take up the same amount of space
    sv.distribution = .fillEqually 
    
    for _ in 0..<50 { 
        // omitting the rounded corners or any other styling because
        // it's not the point of this question
        let subview = UIView()
        // The stack view will determine the width based on the screen size
        // we just need to say that height == width
        subview.widthAnchor.constraint(equalTo: subview.heightAnchor).isActive = true
        sv.addArrangedSubview(subview)
    }
    
    // add your stackview to your view hierarchy and constrain it