Creating a grid of buttons or images in iPhone app is a common requirement now day’s. The problem I am talking about is shown in given below image
To achieve this requirement, we have various approaches
1) Use UITableView
2) Use UICollectionView
3) Create your own grid layout using UIImageView or UIButton(If you want to perform selection)
In this post, I am going to tell you how we can achieve the above requirement using the third technique.
We will use UIScrollView and UIButton’s in building or achieving above requirement and with the help of for loop will iterate through our grid.Below is the code that create a grid of 3 columns as shown in above picture
Don’t worry, I am going to explain the above code though its self explanatory.First we tool three variables xPos = x positon of our button, yPos = y position of our button and lineCount = count to check if we need to add new row.
In second step, we initiated our for loop ( because i need 4*3 grid so i set my limit to 13 in for loop), then i check if i already placed button to third column, I need to add new row that’s why i set new x position, y position and line count. Then we create our button programmatically and gave him respective images for different states.We also assign tag to our button in order to check which button is pressed and give frames to it. Add target to the button and finally add it to our scrollView as a subview.
Lastly we set our scroll contentSize so that it can be scrollable.
Now in the end we will write down our button action and its done.