0

I'm trying to put a UIView (banner) on top of the list (tableView), so the UIview will not disappear when the user scrolls down the list. I tried this code, but didn't work.

override func viewDidLayoutSubviews() {
    self.view.addSubview(banner)
    banner.frame.size.width = self.view.frame.size.width
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    var rect = self.banner.frame
    rect.origin.y = max(0,scrollView.contentOffset.y + scrollView.contentInset.top)
    self.banner.frame = rect
}

Any advice how to fix it? Thank you

lukas28277
  • 97
  • 1
  • 15
  • 1
    Please share your design, what you exact want to do –  Mar 06 '17 at 16:53
  • why are you using scroll view function with a table view? you only defined the width of the banner, what about height? – f_qi Mar 06 '17 at 16:57
  • Are you subclassing your view controller from `UIViewController` or `UITableViewController`? Can you share a screenshot of what you want? – Adeel Miraj Mar 06 '17 at 16:57
  • @f_qi I added height, but no change. – lukas28277 Mar 06 '17 at 17:07
  • @lukas28277 please take a look at the answer by Kyle, I think his approach could solve what you are trying to do. – f_qi Mar 06 '17 at 17:14
  • Possible duplicate of [UITableView with fixed section headers](http://stackoverflow.com/questions/17582818/uitableview-with-fixed-section-headers) –  Mar 06 '17 at 17:19

1 Answers1

2

Instead of trying to keep the view within the scrollView, a much easier method would be to use a standard UIViewController with a UIView attached to the top using AutoLayout with constraints and UITableView attached to the bottom of the UIView and the bottom of the UIViewController.

With this layout, only your smaller tableView would be scrolling and your UIView would be stationary in place, outside the scope of the scrolling UITableViewCells.

If you are currently using an UITableViewController, you'll need to remove the override modifiers from your tableView methods, make your UIViewController implement UITableViewDataSource and UITableViewDelegate, then attach the delegates either in code or storyboard.

Your new UIViewController would look like this at the top:

class MyController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    ...
}
Kyle
  • 14,036
  • 11
  • 46
  • 61
  • Yes, I thought about it, but I thought there should be a way, how to stick the uiview to the top , because it is not the part of the main cells of the list (tableView) – lukas28277 Mar 06 '17 at 17:16
  • @lukas28277 there is. check the duplicate link I just made. –  Mar 06 '17 at 17:19
  • @lukas28277 the fact that the view is not part of the main cells of the list is the exact reason i would recommend my approach. it completely separates this accessory view you are describing from your tableview and the tableview's logic. – Kyle Mar 06 '17 at 17:45