Swift: scrollview after use subviews not work

2019-08-17 14:44发布

问题:

I want add sub view to the scrollview programmatically

If i add subviews to scrollview, scrolling not work

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

I try one view in scrollView but not work again

In normal storyboard work fine, but by addSubView not work

How i can fix it ?

回答1:

First it's better using UIStackView , here you need to add bottom constraint for the last item

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