Swift:使用子视图后滚动视图不起作用

Swift: scrollview after use subviews not work

我想以编程方式将子视图添加到 scrollview

如果我将 subviews 添加到 scrollview,滚动将不起作用

for subview in view.scrollView.subviews {
    subview.removeFromSuperview()
}

var j = 0
for value in getList {
    let viewChild = SelectClass.createMyClassView()
    viewChild.translatesAutoresizingMaskIntoConstraints = false
    viewAll[j] = viewChild

    viewChild.title.text = value.value

    view.scrollView.addSubview(viewChild)

    j = j+1
}

var i = 0
for subview in view.scrollView.subviews {
    let item = subview as? UIView
        NSLayoutConstraint.activate([
            (item?.leftAnchor.constraint(equalTo: view.scrollView.leftAnchor))!,
            (item?.rightAnchor.constraint(equalTo: view.scrollView.rightAnchor))!,
             (item?.heightAnchor.constraint(equalToConstant: 50))!
         ])

     if(i > 0){
         NSLayoutConstraint.activate([
             (item?.topAnchor.constraint(equalTo: (viewAll[i-1]?.bottomAnchor)!))!
         ])
     } else {
         NSLayoutConstraint.activate([
             (item?.topAnchor.constraint(equalTo: view.scrollView.topAnchor))!
         ])
     }

     i = i+1
}

view.scrollView.isScrollEnabled = true

我尝试了 scrollView 中的一个视图,但再次无法正常工作

在正常的情节提要中工作正常,但是 addSubView 不工作

我该如何解决?

首先最好使用UIStackView,这里需要为最后一项添加底部约束

if let last =  viewAll.last {
     NSLayoutConstraint.activate([
         last.bottomAnchor.constraint(equalTo: view.scrollView.bottomAnchor)
     ])
}