Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make UIView in UIScrollView stick to the top when scrolled up

So in a UITableView when you have sections the section view sticks to the top until the next section overlaps it and then it replaces it on top. I want to have a similar effect, where basically I have a UIView in my UIScrollView, representing the sections UIView and when it hits the top.. I want it to stay in there and not get carried up. How do I do this? I think this needs to be done in either layoutSubviews or scrollViewDidScroll and do a manipulation on the UIVIew..

like image 723
xonegirlz Avatar asked Jun 30 '12 08:06

xonegirlz


People also ask

How do I make my UI view scrollable?

You cannot make a UIView scrollable. That's what UIScrollView is for. However if you are using storyboards you can try to add constraints to the view so when you rotate the device the content remains inside the viewable area.

What is scroll view in Swift?

The scroll view displays its content within the scrollable content region. As the user performs platform-appropriate scroll gestures, the scroll view adjusts what portion of the underlying content is visible. ScrollView can scroll horizontally, vertically, or both, but does not provide zooming functionality.


2 Answers

To create UIView in UIScrollView stick to the top when scrolled up do:

func createHeaderView(_ headerView: UIView?) {
    self.headerView = headerView
    headerViewInitialY = self.headerView.frame.origin.y
    scrollView.addSubview(self.headerView)
    scrollView.delegate = self
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let headerFrame = headerView.frame
    headerFrame.origin.y = CGFloat(max(headerViewInitialY, scrollView.contentOffset.y))
    headerView.frame = headerFrame
}
like image 148
evya Avatar answered Sep 21 '22 13:09

evya


Swift Solution based on EVYA's response:

var navigationBarOriginalOffset : CGFloat?

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    navigationBarOriginalOffset = navigationBar.frame.origin.y
}

func scrollViewDidScroll(scrollView: UIScrollView) {
    navigationBar.frame.origin.y = max(navigationBarOriginalOffset!, scrollView.contentOffset.y)
}
like image 32
Scott Byrns KCL Avatar answered Sep 21 '22 13:09

Scott Byrns KCL