To start off: Create a single view app in XCode and follow along!
In order to draw in Swift we will need a custom UIView that we can add to our ViewController. Let's create one named DrawView, it will inherit from UIView. We will add two init methods, override the draw and add a method stub to draw a line like so:
Don't forget to add your custom view to your ViewController in the ViewDidLoad!
Now lets draw a line from the top corner to the bottom corner. To get the top left corner we can use the bounds of the frame: bounds.origin.x and bounds.origin.y this gives use the coordinates of (0,0). To get the bottom corner we can get the width and height of the device by using bounds.width and bounds.height.
To draw the line we will use the UIBezierPath class to create a path and tell it to start at the top left and draw a path to the bottom right, we will also set the colour to red and call the stroke to draw the line on the path and fill to fill the line with the current drawing properties (the red in this case):
Here is how it looks:
var leftToRight = Math.random() >= 0.5;
Luckily for us Swift developers we can just make use of the Bool.Random function to return us a random boolean value.
let leftToRight:Bool = Bool.random()
Lets change our drawLine method to randomly draw a diagonal line
After a couple tries reloading the simulator I finally got a right to left line:
The Swift way to do this is to use the stride function. In the code below the start is the x value, through to the width of the screen by the step value.
This is what we end up with! The best part is it will work on any size device!