Instead of StackView, better to use UICollectionView, as you can then use the FlowLayout of the UICollectionView, and create 64 cells GridView for your chessboard.
I made a GitHub Repo which does that, go to SecondViewController Code: SourceCode
Explanation:
Step 1: Make the collection View width as the multiple of 8 occupying maximum screen width.
override func viewDidLoad() {
super.viewDidLoad()
let deviceWidth = UIScreen.main.bounds.size.width
let cellWidth = floor(deviceWidth / 8)
let collectionViewWidth = 8 * cellWidth
self.collectionViewWidthConstraint.constant = collectionViewWidth
}
Step 2: Define the size of the collectionCell
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let deviceWidth = UIScreen.main.bounds.size.width
let width = floor(deviceWidth / 8)
let height = width
return CGSize(width: width, height: height)
}
Step 3: Define the total number of cells and color of each cell
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 64
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "unique", for: indexPath)
let chessRow = indexPath.row / 8
if chessRow % 2 == 0 {
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor.white
}else{
cell.backgroundColor = UIColor.black
}
} else{
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor.black
}else{
cell.backgroundColor = UIColor.white
}
}
return cell
}
Step 4: Set the collectionView aspectRatio to 1 in storyboard constraints.
Final Outcome: 