简体   繁体   中英

iOS constraints not working in UIScrollView

I have an application which layouts views of child view controllers in a UIScrollView. Views are created from storyboard with storyboard.instantiateViewControllerWithIdentifier() . The problem is that constraints do not position views correctly if the view is not displayed on screen. The strange thing is, that constraints fix themselves when you interact with the view (press a button or start scrolling). Functions like setNeedsDisplay(), setNeedsLayout, updateConstraints etceteras don't work.

EDIT:
Code used for loding views to UIScrollView

for i in 0..<viewControllers.count {
    addChildViewController(viewControllers[i])
    viewControllers[i].view.frame = CGRect(x: CGFloat(i) * scrollView.bounds.size.width, y: 0, width: scrollView.bounds.size.width, height: scrollView.bounds.size.height)

    scrollView.addSubview(viewControllers[i].view)
}

After some testing I have found that this is a bug in the SDK and that iOS 9 fixes the bug. I have found only one way to fix the problem on iOS 8. That is to set the content offset of scroll view before the view gets added to the scroll view as a subview. The code used for loading views to scroll view is:

for i in 0..<viewControllers.count {
    scrollView.contentOffset.x = CGFloat(i) * view.bounds.size.width

    addChildViewController(viewControllers[i])
    viewControllers[i].view.frame = CGRect(x: CGFloat(i) * scrollView.bounds.size.width, y: 0, width: scrollView.bounds.size.width, height: scrollView.bounds.size.height)

    scrollView.addSubview(viewControllers[i].view)
}

scrollView.contentOffset.x = 0.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM