0

I have an UIView in ScrollView superview. I want this UIView to stick to the top and stays there when users scrolls down.

Note that it should start in the middle of a screen and go up respectively when scrolling down.

enter image description here

I've seen many questions and answers but none of them solved my problem

iOS: Add subview with a fix position on screen

Simple way to change the position of UIView?

My code in scrollViewDidScroll method

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    if scrollView.contentOffset.y > anchor.frame.origin.y {

        var fixedFrame:CGRect = self.anchor.frame
        fixedFrame.origin.y = (self.navigationController?.navigationBar.frame.height)!
        self.anchor.frame = fixedFrame


    }

}
theDC
  • 6,364
  • 10
  • 56
  • 98
  • Is that view at the top of it at the beginning, or is it somewhere else and have other view above it? – Larme Jun 14 '17 at 11:53
  • It's in the middle of the scrollView, bounded by constraints, maybe this is a problem? – theDC Jun 14 '17 at 11:53
  • Shouldn't, it just that if it was already at the top, the easiest way would have to not put it in the scroll view and start the frame of the scroll view starting from that sticky view. – Larme Jun 14 '17 at 11:55
  • But if I don't put it into scrollView, how to make it go up when scrolling down? – theDC Jun 14 '17 at 11:57
  • Maybe just use TableView with sections? By default sections headers sticks to top during scroll. – Michał Kwiecień Jun 14 '17 at 12:07
  • @MichałKwiecień this is not my usecase, I'd like to have it as a UIButton which I'm going to animate when it reaches the top or navbar – theDC Jun 14 '17 at 12:16
  • @DCDC - your question is not clear. You want View to start in middle of scroll view... then you say it should *"go up respectively when scrolling down"*??? Do you mean if the user drags down, the *other* content in the scroll view should scroll down while this view moves up? – DonMag Jun 14 '17 at 13:56

2 Answers2

0

you can do this by saving a initial offset value of Y for your anchor view, then compare it in the scrollview delegate event.

self.initialOffSet = self.anchor.frame.origin.y

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    var newFrame = self.anchor.frame

    newFrame.origin.y = max(self.initialOffSet!, scrollView.contentOffset.y)

    self.anchor.frame = newFrame
}
titan
  • 524
  • 1
  • 6
  • 19
-1

Why dont you put that view out of your scrollview?It will stay at the top only even when you will be scrolling your scrollview?

Garima Saini
  • 173
  • 8