How to set content size of UIScrollView dynamically

前端 未结 11 1936
耶瑟儿~
耶瑟儿~ 2020-12-01 05:41

I got question about UIScrollview.

The story is I have a UIView named ChartsView which I re-draw it myself by override method drawRec

11条回答
  •  孤街浪徒
    2020-12-01 06:06

    Calculate UIScrollview contentSize dynamically(depending subviews frame)

    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;
                           });
    }
    

提交回复
热议问题