Scrollview only showing last dynamically added subview

I am trying to add a view from my storyboard to a UIScrollView. I need to add the view an X amount of times and I do this with a for loop

sectionViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SectionViewController") as! SectionViewController

...

for index in 0..<numberOfSections {
            let subViewFrame = CGRectMake(self.scrollView.frame.size.width * CGFloat(index), -64, self.view.frame.size.width, self.view.frame.size.height)

            let subView = sectionViewController.view
            subView!.frame = subViewFrame
            subView.tag = index

            self.scrollView .addSubview(subView!)
        }

The ScrollView is created programmatically like this

self.scrollView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)

self.scrollView.pagingEnabled = true
self.scrollView.alwaysBounceVertical = false

self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * CGFloat(numberOfSections), 0)
self.scrollView.scrollsToTop = false

scrollViewFrame = CGRectMake(0, 100, self.scrollView.frame.size.width, self.scrollView.frame.size.height)

self.scrollView.frame = scrollViewFrame

self.view.addSubview(self.scrollView)

So I add the subViews after this. The problem is that only the last subview is showing. So when numberOfSections = 10, only the 10th subview is showing. What am I doing wrong here?


而不是为所有索引(subView = sectionViewController.view)分配与子视图相同的视图,为每个索引创建不同的SectionViewController视图实例


在@Annie_Dev的建议尝试为偶数分配不同的颜色并添加子视图以检查是否添加子视图。


So after a lot of digging around and trying a bunch of things, I finally found the problem. I had a lot of conflicting constraints in my subview. Once I had fixed those, everything showed up like it should.

链接地址: http://www.djcxy.com/p/74390.html

上一篇: AutoMapper:“忽略其余”?

下一篇: 滚动查看只显示上次动态添加的子视图