Five Steps to Create a Chess App 3/5
Step 3: drawing the chess board
Step 1 created the app and step 2 put a view on screen. Now let’s draw the 8x8 chess board. We need to create a file to put our code in.
Click “Chess” folder on the left navigation panel and it turns blue. Right click to show the menu.
Select “New File…” to create a new file.
Select “Cocoa Touch Class” under “iOS”. Then click “Next” button to continue.
Name our new class “BoardView”. Make sure it is the subclass of UIView.
Accept the default location and click “Create” button.
The new class file is BoardView.swift. Now we need to set the class of our canvas, the white view in Main.storyboard, to BoardView. Click “Main.storyboard” on the left navigation panel.
With our white view selected, find the credit card like icon near the top right corner. Click it so we can change Class from UIView to our own BoardView.
And we can see on the left pane that “View” becomes “Board View”. Click the 3rd icon from right on the top bar to show the left navigation panel in case it was hidden.
Go back to BoarView.swift to input source code shown below. The execution entry point is the Xcode provided function “draw”. We created 3 functions to do the job of drawing 64 squares. Sorry for the hardcoded value 80, which is the side of each square. Remember we set the board size 640x640 on purpose when we added the white canvas view onto the big yellow view?
Launch the app to view our gorgeous board view.
And here is the text version of BoardView, for your convenience.
import UIKitclass BoardView: UIView { override func draw(_ rect: CGRect) {
drawBoard()
} func drawBoard() {
drawTwoRowsAt(y: 0 * 80)
drawTwoRowsAt(y: 2 * 80)
drawTwoRowsAt(y: 4 * 80)
drawTwoRowsAt(y: 6 * 80)
}
func drawTwoRowsAt(y: CGFloat) {
drawSquareAt(x: 1 * 80, y: y)
drawSquareAt(x: 3 * 80, y: y)
drawSquareAt(x: 5 * 80, y: y)
drawSquareAt(x: 7 * 80, y: y)
drawSquareAt(x: 0 * 80, y: y + 80)
drawSquareAt(x: 2 * 80, y: y + 80)
drawSquareAt(x: 4 * 80, y: y + 80)
drawSquareAt(x: 6 * 80, y: y + 80)
}
func drawSquareAt(x: CGFloat, y: CGFloat) {
let path = UIBezierPath(rect: CGRect(x: x, y: y, width: 80, height: 80))
UIColor.lightGray.setFill()
path.fill()
}
}