How to set content size of UIScrollView dynamically

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

    Thanks to IOS Rocks and CularBytes for the leads on this. I found two problems (for me) with the above solutions:

    1. I always have a container UIView as the only child of my UIScrollView, so I had to update the way I look up the last view in that child UIView (see below)
    2. I am offset'ing my content in the UIScrollView and as such needed to calculate the absolute position of that last UIView (so, relative to the window not the parent view)

    Also I am using autolayout to pin the sides of the UIScrollView, so I don't need to worry about width (as is CularBytes).

    Here's what I came up with and works (in Swift 3.0):

    func setScrollViewContentSize() {
    
        var height: CGFloat
        let lastView = self.myScrollView.subviews[0].subviews.last!
        print(lastView.debugDescription) // should be what you expect
    
        let lastViewYPos = lastView.convert(lastView.frame.origin, to: nil).y  // this is absolute positioning, not relative
        let lastViewHeight = lastView.frame.size.height
    
        // sanity check on these
        print(lastViewYPos)
        print(lastViewHeight)
    
        height = lastViewYPos + lastViewHeight
    
        print("setting scroll height: \(height)")
    
        myScrollView.contentSize.height = height
    }
    

    I call this in my viewDidAppear() method.

提交回复
热议问题