Josh O'Connor Josh O'Connor - 1 year ago 170
iOS Question

Collapse a view on scroll up (iOS)

I have a ViewController, which has a tableView, and has two views on top of the table view. I need to collapse a view (outlined in red in the image), when the user scrolls up, and move another view (orange button), up with the table. I'm planning on using the scrollViewDidScroll delegate method to detect the offset of the table, and handle the collapsing with that.

How do I go about implementing this?

enter image description here
enter image description here

//Custom delegate method, which returns offset of scrollViewDidScroll
func didScrollScrollView(offset: CGFloat){
//I have the offset, which is -30 on load. How do I implement collapsing of the view highlighted in red?


Answer Source

you need to access the frame of the view or better its heightConstraint. If you have a reference to the heightConstrain you can do:

var previousOffset: CGFloat = -30
func didScrollScrollView(offset: CGFloat){
    let diff = previousOffset - offset
    previousOffset = offset

    var newHeight = heightConstraint.constant + diff

    if newHeight < 0 {
        newHeight = 0
    } else if newHeight > 60 { // or whatever
        newHeight = 60
    heightConstraint.constant = newHeight

If you don't use Autolayout you need to update the frames manualy.

Also set clipsSubviews=true (clippedToBounds) in interface builder or in code

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download