Stackview doesn't append second view

2019-09-15 00:34发布

I've created a stack view programmatically and I added a view which I've created programmatically too to it. But when I try to add a second view it doesn't work. Here's my code:

@IBOutlet weak var codingScrollView: UIView!
let codeStackView = UIStackView()
var codeViews = [CodeView]()
let codeView1 = CodeView(name: "Lennart", date: "13/05/2002", code: "Just some code")
let codeView2 = CodeView(name: "Nina", date: "01/07/1999", code: "Also some code")

The codingScrollView is the contentview I've added to a UIScrollView. The codeStackView is the one I've described before The codeViews array is being used to add the views to the stackview.

Here's the viewDidLoad method:

    codeViews.append(codeView1)
    codeViews.append(codeView2)

    codingScrollView.addSubview(codeStackView)
    codingScrollView.backgroundColor = UIColor(red: 226/255, green: 226/255, blue: 226/255, alpha: 1)

    codeStackView.centerXAnchor.constraint(equalTo: codingScrollView.centerXAnchor)
    codeStackView.centerYAnchor.constraint(equalTo: codingScrollView.centerYAnchor)

    codeStackView.translatesAutoresizingMaskIntoConstraints = false

    codeStackView.spacing = 10

    codeStackView.axis = .horizontal
    codeStackView.alignment = .center

    for i in 0...codeViews.count - 1 {
        codeStackView.addSubview(codeViews[i])
        codeStackView.addArrangedSubview(codeViews[i])
    }

But if I run the app it won't show the second view, it only shows one of them.

Thank you very much, I really appreciate any kind of help

1条回答
虎瘦雄心在
2楼-- · 2019-09-15 01:15

Try adding the codeView{1,2} to the stack view first then add the codeStackView to the codingScrollView.

Also, be sure to set codeStackView.translatesAutoresizingMaskIntoConstraints = false before doing any constraints.

codeViews.append(codeView1)
codeViews.append(codeView2)

for i in 0...codeViews.count - 1 {
    codeStackView.addSubview(codeViews[i])
    codeStackView.addArrangedSubview(codeViews[i])
}

codeStackView.translatesAutoresizingMaskIntoConstraints = false

codeStackView.centerXAnchor.constraint(equalTo: codingScrollView.centerXAnchor)
codeStackView.centerYAnchor.constraint(equalTo: codingScrollView.centerYAnchor)

codeStackView.spacing = 10

codeStackView.axis = .horizontal
codeStackView.alignment = .center

codingScrollView.addSubview(codeStackView)
codingScrollView.backgroundColor = UIColor(red: 226/255, green: 226/255, blue: 226/255, alpha: 1)
查看更多
登录 后发表回答