We can use a stretching header in our application. It becomes easier to create because by default iOS gives you the bouncy backs to table views and scroll views.
Follow the steps to create the stretcher header or we can say that parallax animation on the table view header:-
- First, drag a table view From Storyboard to your View Controller.
- Then for the table view header create Xib of UIView which will contain your table view header content like this:-
Create the object of your header View and initialize header view xib from the bundle.
1 2 3 |
var headerView : ProfileHeader? headerView = (Bundle.main.loadNibNamed("ProfileHeader", owner: self, options: nil)?[0] as? ProfileHeader)! headerView?.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH/2) |
Set table view estimation row height and assign header view to the table header view.
1 2 |
profileTableView.estimatedRowHeight = UITableViewAutomaticDimension profileTableView.tableHeaderView = headerView |
Remove the header from the table header view and also set the table view contentInset according to the size you need of the header
1 2 3 |
profileTableView.tableHeaderView = nil profileTableView.contentInset = UIEdgeInsets(top: SCREEN_WIDTH/2, left: 0, bottom: 0, right: 0) profileTableView.addSubview(headerView!) |
Manage y origin of a header according to when the user scrolls the table view.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { self.profileTableView.reloadData() } func scrollViewDidScroll(_ scrollView: UIScrollView) { if headerView != nil { let yPos: CGFloat = -scrollView.contentOffset.y if yPos > 0 { var imgRect: CGRect? = headerView?.frame imgRect?.origin.y = scrollView.contentOffset.y imgRect?.size.height = SCREEN_WIDTH/2 + yPos - SCREEN_WIDTH/2 headerView?.frame = imgRect! self.profileTableView.sectionHeaderHeight = (imgRect?.size.height)! } } } |
You can also add the blur effect to the header of the table view
1 2 3 4 5 6 7 8 |
func blur(){ let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = (headerView?.bannerImage.bounds)! blurEffectView.alpha = 0.9 blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] headerView?.bannerImage!.addSubview(blurEffectView) } |
You can call this method in view of did load of the controller. So you have successfully added a stretchy header in your app.
Thanks for going through this blog. Stay cool and stay updated.