How to set content size of UIScrollView dynamically

前端 未结 11 1915
耶瑟儿~
耶瑟儿~ 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:01

    It is not 100% guaranteed that the last object in scrollView.subviews array will return the highest y-origin object in your scroll view. The subviews array is arranged by Z-Index (i.e the last object in the subviews array will be the object stacked the highest and will be the top-most subview in the scroll view's subviews. Instead it is more accurate to use a basic sort function to iterate through the subviews and get the object with the highest y-origin.

    Swift 4

    extension UIScrollView {
        func updateContentView() {
            contentSize.height = subviews.sorted(by: { $0.frame.maxY < $1.frame.maxY }).last?.frame.maxY ?? contentSize.height
        }
    }
    

    Usage (in viewDidLayoutSubviews or whenever your content size updates):

    myScrollView.updateContentView()
    

提交回复
热议问题