How To Use UIStackView Like TableView

Gorkem Gur
Mobiroller Tech
Published in
2 min readSep 19, 2022

In this article we are going to learn how to use UIStackView as UITableView and UIView as UITableViewCell.

So why do we need this usage?

  • If you don’t want to define or deal with tableview’s data source and delegate methods so long story short if you want to reduce complexity you can choose to use UIStackView,
  • You may have to use a scrollview on the page to be designed, etc.

We set our use case in the list above. Now we have to think about how to set up an algorithm to use UIStackView as TableView.

First, we need a UIView to display the incoming data. Then when this UIView is clicked we need to get the clicked index and the model from clicked view.

So let’s create a design file (I used xib but you can use storyboard or whatever you want like programmatically it does not matter).

Basic Design For Usage StackView

Then, We will use the nibloadable extension to create our interface. We need to integrate Nibloadable to our custom View , like the below code.

We should create UIStackViewExtension

We will create UIStackViewExtension in terms of readability, we do not want complicated code blocks in ViewController.

After the create this extension we need to use these function in our ViewController with UIStackView.

Let’s check ExampleStackViewController

ExampleStackViewUsageViewController File

We will do main operations via above codes. If you can look carefully we added tag to each MockView because we need to get clicked index when user tapped the rows of stackView.

There are 2 items to consider here.

  • You need to set UITapGestureRecognizer in for loop for each MockView,
  • You have to add tags in for loop and use these tags in TapGestureRecognizer function to get the row the user clicked.

That’s it you can use your UIStackView as UITableView, long story short our UIStackView becomes UITableView and our MockView becomes UITableViewCell now.

ExampleStackViewUsage App Preview

I have tried to cover most of the things, but if something left please feel free to ask me :)

You can check full code of Project here:

--

--