1

enter image description here

I am creating this chess game. for building this board i am taking 64 small views and have placed all of them in stack view. but every time i am find that views of one or two rows or columns have not same size as rest of the columns and rows (which have same size views). For example :- In this image the 2nd and 6th columns and 2nd and 6th rows have size (67.67 , 67) where all the rest views have size (67, 67) . why this is happening ? How to make all the view with exact same size?

Thanks

Tapan Raut
  • 73
  • 7

1 Answers1

1

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: Chessboard

Deep Arora
  • 1,900
  • 2
  • 24
  • 40
  • Thanks for your responce Deep. can we use gesture recogniser in collection view to move the object from one cell to other cell as like chess game ? – Tapan Raut Aug 22 '18 at 19:33
  • Yes, you can do. Try to do it, if you face any problem, mention the problem that comes and I will try to check. – Deep Arora Aug 23 '18 at 05:13