如何以编程方式将 SubView 添加到水平 StackView 以创建条纹? [英] How to add SubView to a horizontal StackView programmatically to create Stripes?

查看:29
本文介绍了如何以编程方式将 SubView 添加到水平 StackView 以创建条纹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 StackView 的 collectionView Cell.

I have a collectionView Cell with a StackView in it.

class OuterCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var stackView: UIStackView!
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        for i in 1...30 {
            let tick = UIView()
            if i % 2 == 0 {
                tick.backgroundColor = UIColor.red
            } else {
                    tick.backgroundColor = UIColor.clear
            }
            tick.tag = i
            tick.heightAnchor.constraint(equalTo: self.heightAnchor, constant: 0.0).isActive = true
            self.stackView?.insertArrangedSubview(tick, at:i)
        }
    }

我想在 stackView 上在 red 和 clear 之间交替绘制 30 个单元格.现在我正在设置子视图的索引以及具有自动布局锚点约束的高度,并希望 .fillEqually 分布将计算每个子视图的宽度和 X 位置.但是现在,当我尝试设置高度锚点时它会崩溃,并且当我移除高度锚点时根本不显示任何内容.我如何将它们布置成全高,并且彼此相邻且没有边距?

I want to draw 30 cells on the stackView alternating between red and clear . Right now I am setting the index of the subview as well as the height with a auto layout anchor constraint and hoping that the .fillEqually distribution will compute the width and X locations of each of the subviews. However right now, it crashes when I try and set the height anchor and simply doesn't show anything when I remove the height anchor. How do I lay these out such that they are full height, and right next to each other with no margins?

推荐答案

我认为您不应该在此处向堆栈视图中的项目添加高度锚点.自动地,堆栈视图中包含的事物具有相等的高度(或宽度取决于堆栈视图的方向).您不需要直接在 stackview 中设置大小.它首先违背了堆栈视图的目的.

I think that you shouldn't be adding a height anchor here to items within your stackview. Automatically, things contained in the stack view are equal heights (or widths depending on stackview orientation). You shouldn't need to be setting sizes within the stackview directly. It defeats the purpose of the stackview in the first place.

这篇关于如何以编程方式将 SubView 添加到水平 StackView 以创建条纹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆