Auto layout UIScrollView with subviews with dynamic heights

后端 未结 6 1168
情书的邮戳
情书的邮戳 2020-11-29 19:28

I\'m having troubles with UIScrollView using auto layout constraints. I have the following view hierarchy, with constraints set through IB:

- ScrollView (lea         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 19:47

    Use this code. ScrollView setContentSize should be called async in main thread.

    Swift:

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
        DispatchQueue.main.async {
            var contentRect = CGRect.zero
    
            for view in self.scrollView.subviews {
               contentRect = contentRect.union(view.frame)
            }
    
            self.scrollView.contentSize = contentRect.size
        }
    }
    

    Objective C:

     - (void)viewDidLayoutSubviews {
         [super viewDidLayoutSubviews];
    
         dispatch_async(dispatch_get_main_queue(), ^ {
                            CGRect contentRect = CGRectZero;
    
                            for(UIView *view in scrollView.subviews)
                               contentRect = CGRectUnion(contentRect,view.frame);
    
                               scrollView.contentSize = contentRect.size;
                           });
    }
    

提交回复
热议问题