Stretchable Table View Header using Storyboard

Lucas Coelho
2 min readJun 23, 2020

--

Here’s a pretty common, simple, and beautiful UX you can easily add to your projects. This is a beginner level tutorial and you should get it working in only a few minutes.

This is the feel we wanted to our original profile screen in Listory iOS app, so let’s get to it with a clean and elegant approach:

On Xcode, create a new project and select Single View App.

Select ViewController.swift file on your project navigator and add the table view’s data source and delegate:

extension ViewController: UITableViewDataSource {    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        return 0    }    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        return UITableViewCell()    }}extension ViewController: UITableViewDelegate {    func scrollViewDidScroll(_ scrollView: UIScrollView) {        if scrollView.contentOffset.y < 0 {            headerHeight.constant = 250 - scrollView.contentOffset.y        } else {            headerHeight.constant = 250        }    }}

On the same file, add an outlet for the image’s height:

@IBOutlet weak private var headerHeight: NSLayoutConstraint!

UITableView is a subclass of UIScrollView, meaning you can use the scrollViewDidScroll method for the table view.

Let’s proceed to the storyboard. Open Main.storyboard and drag a UITableView to your ViewController. Add top, bottom, leading, and trailing constraints, and don’t forget to uncheck constrain to margins. Set them all to 0.

Right-click on the table view to connect the data source and the delegate to the View Controller.

Drag a UIView to the table view, this will be our header. Resize it to the height you want it to be. I will set it to 250 points (and that’s the minimum height I’m using on ViewController.swift).

Now drag a UIImageView to the header and add all four constraints. Add a height constraint as well and connect it to the outlet. Add a horizontally center constraint and a ratio. Next, delete the image view’s top, leading, and trailing constraints leaving in only ratio, height, and bottom constraints.

Change the image’s content mode to Aspect Fill. Lastly, add an image to the image view.

That’s it! Command + R to run the project and check it on the simulator

Full project available here.

If you’d like to see all iOS articles written by me you can check my list out on Listory.

--

--