Category Archives: Swift

How to draw a triangle in Apple Watch

I’ve previously covered how to draw circles and rectangles into an image when writing an Apple Watch app. I had an idea for another watch face that needed triangles – these need a different approach using Watch Kit. Basically, you have to draw a path around the perimeter of the triangle (or any other shape), then fill in the shape. Here’s a function to draw a triangle that points to the left:

    internal func drawTriangle( _ context : CGContext?, centreX : CGFloat, centreY : CGFloat, size : CGFloat, colour : CGColor )
        context?.move(to: CGPoint(x: centreX - size/2.0, y: centreY))
        context?.addLine(to: CGPoint(x: centreX + size/2.0, y: centreY - size/2.0))
        context?.addLine(to: CGPoint(x: centreX + size/2.0, y: centreY + size/2.0))

And this is the code for drawing a rectangle:

    internal func drawRectangle( _ context : CGContext?, centreX : CGFloat, centreY : CGFloat, width : CGFloat, height : CGFloat, colour : CGColor )
        let origin = CGPoint( x: centreX - width/2.0, y : centreY - height/2.0 )
        let rect = CGRect( origin : origin, size : CGSize(width: width, height: height) )

Once you can do those primitive triangle/rectangle operations, you can put them together to render any digit you like. So I used them to draw a ‘timeometer’ in this speedo watch face:

The dial is rendered as a series of ticks – at the moment, it shows minutes and hours. I have to admit I still tend to read the time from the digits at the bottom, so I may change the dial to show seconds and minutes instead.

Leave a comment

Filed under Programming, Swift

How to switch watch faces using swipe gestures

A welcome addition to WatchKit 3.0 is the swipe gesture recognizer.  Previously, I used an ordinary button to switch between modes in my Watch Face app, but now I can mimic the behaviour of official watch faces by swiping left or right.

The change is quite simple to make too. First, you just need a Group control that contains an image (into which you’ll draw the watch face). Then, you drag a couple of Swipe Gesture Recognizers into the group, and change the properties so that one is a left swipe and the other is a right swipe.

Having done that, you need to insert an action for each of the gestures – you can do that by control-dragging from the gesture in the storyboard outline into the InterfaceController code. Make sure to add an action (rather than an outlet) – that way, Xcode will create a stub method for you with the correct signature.

The logic for the swipe gesture just switches between watch faces then re-draws the time:

    // Tissot --> Hermes --> Roman
    @IBAction func swipeRight(_ sender: Any) {
        switch (
        case WatchFaceId.tissot: watchFace = HermesWatchFace()
        case watchFace = RomanWatchFace()
        case WatchFaceId.roman: watchFace = TissotWatchFace()
        drawTime() // refresh with updated background & different styles

and the left swipe reverses the transition order.

See also this earlier post that explains how you can draw directly into an image in WatchKit – combined with the swipe gesture recogniser, it provides a neat way to switch between different modes in any app.

Leave a comment

Filed under Swift

How to use the Digital Crown in a Watch Face App

I’ve written before that, having lived with the Apple Watch for a while, I felt the watch faces lacked variety. So, I wrote a watch face app, which I now use for the majority of the time.

For my next watch face, I thought it would be pretty cool to recreate the look of my beloved Tissot watch. One of its best features is that extra functionality is controlled by twisting/pressing the bezel. It supports date/time/stopwatch/timer – or you can hide the digital display altogether. Although WatchKit doesn’t allow you to capture a button press, you can use the digital crown to scroll between choices – so I thought I’d offer a couple of date formats as well as the option to hide the date altogether. tissot

Add a Picker control onto your storyboard and connect it to a WKInterfacePicker in your InterfaceController. There are a number of styles that you can choose, but for my purposes, I chose the default List style:
Then it’s a matter of populating the picker’s list of items – for example, this code could go in function awake(withContext):

            let blankLine = WKPickerItem()
            blankLine.title = ""
            let currentDate = Date()
            let dayDateMonthLine = WKPickerItem()
            dayDateMonthLine.title = "\(currentDate.dayOfWeek()) \(currentDate.dayOfMonth()) \(currentDate.monthAsString())"
            let dateMonthYearLine = WKPickerItem()
            dateMonthYearLine.title = "\(currentDate.dayOfMonth()) \(currentDate.monthAsString()) \(currentDate.year())"
            InfoPicker.setHidden( false )
            InfoPicker.setItems( [ blankLine, dayDateMonthLine, dateMonthYearLine, blankLine ] )

I set the focus on the picker so that the digital crown is immediately responsive (otherwise, you’d have to select the picker first on the touch screen). I also put a blank line before and after the date formats, to make the usage more natural. The code above also uses some extension methods on Date.

Tissot style watch face

Seeing how good this looks, I think Apple are missing a trick. All of their analogue Apple Watch faces are round – I hope they ship a couple of rectangular faces in the next Watch OS upgrade.


Filed under Programming, Swift

How to draw text onto an image in Apple Watch App

Suppose you want to label an item in your WatchKit App. If you’re able to put a label widget onto the storyboard next to the item, that’s fine – but if you’re using Core Graphics to construct an overlay image, chances are you’ll need to draw the text onto the image too. My ultimate aim was to be able to draw the date on my Watch Face App.

It took some digging to find out how to do this. The obvious candidate was CoreGraphics.CGContextShowTextAtPoint, but that’s deprecated from WatchKit 2.0 onwards. Its replacement is the CoreText library, but “import CoreText” doesn’t find it.


Searching on StackOverflow met with little success, possibly because people’s solutions might work for iPhone Apps but don’t satisfy the restricted API available for WatchKit Apps. However, I found this gem which did work on the Apple Watch.

As a worked example, let’s take the Treasure Map App from an earlier post. It’s natural for a treasure map to indicate what’s buried at the cross. I’ve changed the method signature from the one on StackOverflow so that you specify the centre of the text block.

    func drawText( context : CGContext?, text : NSString, centreX : CGFloat, centreY : CGFloat )
        let attributes = [
            NSFontAttributeName : UIFont.systemFontOfSize( 20 ),
            NSForegroundColorAttributeName : UIColor.blackColor()
        let textSize = text.sizeWithAttributes( attributes )
            CGRectMake( centreX - textSize.width / 2.0,
                        centreY - textSize.height / 2.0,
                        textSize.height ),
            withAttributes : attributes )

Calling this from drawCross() in the Treasure Map App results in a neat label underneath the cross:

        drawText( context, text: "Gold", centreX: 100, centreY: 210 )

Screen Shot 2016-08-05 at 08.00.08

Using the same method, I updated my Watch Face App to draw the day and date onto this watch face:

Screen Shot 2016-08-07 at 21.28.23

See also: How to write a Watch Face App for Apple Watch and How to draw on top of an image in Apple WatchKit

1 Comment

Filed under Programming, Swift

How to write a Watch Face App for Apple Watch

Having owned an Apple Watch for over a year, I’ve grown a little bored with the available watch faces. So I was very impressed with the new, special edition Hermes watch face. This is quite different to any of the other faces on the Apple Watch. Unfortunately, it’s only available to new purchasers who buy the brand new Hermes Apple Watch – starting at £1000.

Having written my first Watch App recently, I thought I’d have a go at writing a Watch Face App. Apple WatchKit doesn’t officially support writing watch faces, so this would have to be an ordinary App that happens to display the time. There are plenty of custom faces you can use as wall-paper to create an attractive digital watch, but I wanted the analogue look.

The approach I took was:

  • Start with an image e.g. from the custom faces library
  • Look up how to get the current time in the WatchKit API
  • Find out how to draw graphics on top of an image
  • Work out the maths to draw the hands in the right place
  • Work out how to render proper watch hands

I already blogged about how to get the current time and how to draw graphics on top of an image. So if you followed along, you can replace your Treasure Map image with a watch face image and use the createContext(), drawLine() and applyContextToImage() methods to draw the hour and minute hands. In fact, by making the colour a parameter of drawLine(), you’ve got the method to draw the second hand too.

As for the maths to draw the hands in the right place, it’s trigonometry. Both sin and cos are available in WatchKit, so convert the hours/minutes into radians and calculate the end coordinate of your watch hand, treating the length of the hand as the hypotenuse of a right-angled triangle.

[edit]I had a request to post the maths for this. Suppose you want to draw a hand at 12 minutes past. Convert that into a fraction of how far the hand has moved – here, 12 mins out of a possible 60 mins. Then work out whether it’s in the top-right, bottom-right, bottom-left or top-left quadrant of the watch face (that affects which sin/cos functions you’ll use) – here, 12/60 = 0.2, so it’s between 0.0 and 0.25, hence it’s in the first quadrant.

To calculate the x and y coordinates for the top-right quadrant, we form a right-angled triangle between the hand and the y-axis. The hand forms the hypotenuse of the triangle, let’s choose length = 100. So knowing the minutes as a fraction, and the length of the hand, here’s a function to calculate the x and y coordinates as an offset from the centre of the watch face, using trigonometry:

func handCoordinate( _ fraction : CGFloat, length : CGFloat ) -> (x : CGFloat, y : CGFloat )
    let x : CGFloat, y : CGFloat

    if ( 0 <= fraction && fraction < 0.25 )
        let theta = CGFloat( (fraction/0.25) * π / 2.0 )
        x = length * sin( theta )
        y = -1.0 * length * cos( theta )
        // remaining quadrants left as exercise for the reader!
    return (x,y)

The simplest way of drawing the hand is then a simple drawLine() from (centreX, centreY) to (centreX + x, centreY + y). For my 42mm watch, centreX and centreY are (156,150) – other sizes will vary.

That leaves the trick of how to draw a proper watch hand given only the drawLine() and drawCircle() methods. This is the method I used:


In order to draw the white circle outline with solid black inner-circle, I used this method:

    func drawCircle( context : CGContext?, radius : CGFloat, centreX : CGFloat, centreY : CGFloat, colour : CGColor )
        let diameter = radius * 2.0
        let rect = CGRect( x: centreX - radius, y : centreY - radius, width : diameter, height : diameter )
        CGContextSetFillColorWithColor( context, UIColor.blackColor().CGColor )
        CGContextFillEllipseInRect( context, rect )
        CGContextSetLineWidth( context, 2.0 )
        CGContextSetStrokeColorWithColor( context, colour )
        CGContextStrokeEllipseInRect( context, rect )

There are a couple of limitations:

That said, I’m really happy with the results:

Watch Face App

This is actually one Watch App – I changed the Image to a Button so that I could iterate through different watch faces by tapping the watch. If you do this, call button.setBackgroundImage on the button instead of image.setImage.

See also: How to draw text onto an image and How to draw on top of an image.


Filed under Programming, Swift

How to draw on top of an image in Apple WatchKit

Suppose you’re writing a simple game for Apple Watch – for example, you might have a treasure map image and you want to render a cross on it in a random position to locate the treasure.
This is tricky, because WatchKit severely limits your options for laying out UI primitives on the screen. For example, if you put a label and an image onto a StoryBoard, it will tile them (rather than letting you put one on top of the other).

The approach I’ve adopted is:

  • Create a Group in the story board and set its background image
  • Add an image view within the Group
  • Create a context and use CoreGraphics to write into it
  • Apply the context to the image view

Set up a new iOS WatchKit App, then drag a Group and Image from the Object Library onto the storyboard:
TreasureMap StoryBoard

In the WatchKit App assets, create a new image set and drag your background image onto the x2 outline:
TreasureMap ImageSet

Set the background image on the group:
TreasureMap SetBackground

Then create an outlet in the InterfaceController for the image – one way is to control-drag from the outline view of the storyboard into the interface controller’s swift file. I called mine OverlayImage to convey the purpose.

Finally, add the code that will leverage the CoreGraphics library to draw into the overlay – the work is done in drawCross() which is called from awakeWithContext(). I’ve split out line and circle drawing methods for clarity.

class InterfaceController: WKInterfaceController {
    // Create by control-dragging to the StoryBoard
    @IBOutlet var OverlayImage: WKInterfaceImage!
    let imageWidth : CGFloat = 312.0
    let imageHeight : CGFloat = 348.0 // 390 - 42 for status bar on 42mm watch
    override func awakeWithContext(context: AnyObject?) {

    override func willActivate() { ... } // standard
    override func didDeactivate() { ... } // standard
    func drawCross()
        // Begin image context and grab context
        let context = createContext()
        // Draw our primitives
        drawLine( context, startX: 75, startY: 150, endX: 125, endY: 200 )
        drawLine( context, startX: 75, startY: 200, endX: 125, endY: 150 )
        drawCircle( context, radius : 10, centreX : 100, centreY : 175 )
        // End by applying our graphics to the Overlay image
        applyContextToImage( context )
    func createContext() -> CGContext?
        // The 'opaque' parameter is false, so that we overlay 
        // rather than the static image underneath
        UIGraphicsBeginImageContextWithOptions( CGSizeMake( imageWidth, imageHeight ), false, 0 )
        let context = UIGraphicsGetCurrentContext()
        CGContextBeginPath( context )
        return context
    func drawLine( context : CGContext?, startX : CGFloat, startY : CGFloat, endX : CGFloat, endY : CGFloat )
        CGContextSetStrokeColorWithColor( context, UIColor.blackColor().CGColor )
        CGContextSetLineWidth(context, 3.0)
        CGContextMoveToPoint( context, startX, startY )
        CGContextAddLineToPoint( context, endX, endY )
        CGContextStrokePath( context )
    func drawCircle( context : CGContext?, radius : CGFloat, centreX : CGFloat, centreY : CGFloat )
        let diameter = radius * 2.0
        let rect = CGRect( x: centreX - radius, y : centreY - radius, width : diameter, height : diameter )
        CGContextSetLineWidth( context, 3.0 )
        CGContextSetStrokeColorWithColor( context, UIColor.blackColor().CGColor )
        CGContextStrokeEllipseInRect( context, rect )
    func applyContextToImage( context : CGContext? )
        let img = UIGraphicsGetImageFromCurrentImageContext()
        OverlayImage.setImage( img )

All being well, you can now run your WatchKit App and check that the black cross and circle have been drawn on top of the background image!

TreasureMap WatchApp


Filed under Programming, Swift

How to write Extension Methods in F# and Swift

I’ve used extension methods for a while in F# as a neat way of adding utility methods to system types. For example, suppose you have a set and want to add some elements to it? You might write something like this:

  let collection = ... // initial set defined elsewhere
  let collection = // add extra elements into collection
    [| 1; 2; 3 |] |> Array.fold (fun (acc : Set<'T>) item -> acc.Add item) collection

You might find yourself writing this snippet frequently and for different container types. Instead of defining the operation every time, it’s better to write an extension method:

namespace MusingStudio.Extensions
module Set =
  let AddMulti (items : seq<'T>) (collection : Set<'T>) =
    items |> Seq.fold (fun (acc : Set<'T>) item -> acc.Add item) collection

Then, by bringing the extensions into scope, we can call AddMulti as if it were part of the system Set interface:

open MusingStudio.Extensions

let main argv = 
    let initial = [| 1; 2; 3 |] |> Set.ofArray
    let updated = initial |> Set.AddMulti [| 4; 5; 6 |]
    printfn "%A" updated
    0 // return an integer exit code

I was looking for a way to get the current time/date in Swift, and found some code on Stack Overflow that uses Extension Methods to do it. I’ve added a couple more methods to get the seconds and day-of-month:

import Foundation

// From:
extension NSDate
    func hours() -> Int
        //Get Hours
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Hour, fromDate: self)
        let hours = components.hour
        //Return Hour
        return hours
    func minutes() -> Int
        //Get Minutes
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Minute, fromDate: self)
        let minutes = components.minute
        //Return Minute
        return minutes
    func seconds() -> Int
        // Get Seconds
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Second, fromDate: self)
        let seconds = components.second
        return seconds
    func day() -> Int
        // Get Day
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Day, fromDate: self)
        let day =
        return day

This simplifies the interface to NSDate:

  // Get the time properties
  let currentDate = NSDate()
  let minutes = currentDate.minutes()
  let hours = currentDate.hours()
  let seconds = currentDate.seconds()
  let dayOfMonth =


Filed under F#, Programming, Swift

Calculator App for Apple Watch

I was surprised that Apple didn’t include a calculator app with the Apple Watch. In the 1980’s, calculator watches were cool – having missed out then, I was keen for my Apple watch to have one.CasioCalculatorWatch

I chose to write my own calculator WatchKit App for fun, rather than purchasing one from the App Store. It’s a good choice for a first project, because the user interface is static and the focus is more on getting up the learning curve of WatchKit development. Here are some of the lessons I learnt in the process.

How to get the text from a WatchKit label
Suppose you’ve set up an outlet for a label that displays the input figures in your app – then you’d expect to be able to get the text back from it:

@IBOutlet var labelSum: WKInterfaceLabel!
labelSum.setText( "42.0" )
let digits = labelSum.getText() // error - does not compile

It seems this is not supported in Xcode 7.2/Watch OS 2.1. Instead, you have to track the state in a variable and use that to populate the label.
How to store state in a WatchKit App
For a calculator App at least, you need a state machine to keep track of state, because at different stages you may be inputting the first or second number in the calculation, or re-using the previous answer in another calculation. Swift enum is a discriminated union that is well suited to this:

// Define enum type outside your interface controller
enum CalculationState
    case BuildingLHS( String )
    case BuildingRHS( LHS : String, Op : Operation, RHS : String ) // Waiting for Equals
    case WaitingForOperation( String ) // Got answer already, may do another operation

// Declare a variable to hold the state 
// as a member inside the interface controller class
class InterfaceController: WKInterfaceController {
    // ...
    var state : CalculationState

Use ‘RelativeToContainer’ to scale layout
When defining the UI elements on your story board, the interface controller is only approximately the size of the watch screen. My UI has all the buttons displayed at once, so it’s important to make maximum use of the screen size.
Calc - RelativeToContainer
Here, buttons 7, 8 and 9 are in a horizontal group. To fill that container, we need to use the ‘RelativeToContainer’ scaling style and fill in the proportion each UI element should take. For height, it’s 1 (i.e. the whole container), whereas for width, it’s one third (i.e. 0.33-ish). Personally, I think it would have been more obvious that this is the scaling style to choose if the proportion was displayed as a percentage, rather than a value relative to one.
How to set completion after animation
The WatchKit animation API lacks the ability to specify a completion function that runs after the initial animation changes. This is awkward if you want to flash a UI element from one colour and return to the original colour – if you run both animations in parallel, the colour doesn’t change. I used this code to add an extension method – then I could easily flash UI elements as below:

    func flashSum( origColor : UIColor, flashColor : UIColor ){
            animations: { () -> Void in self.labelSum.setTextColor( flashColor ) },
            completion: { () -> Void in self.labelSum.setTextColor( origColor )}

How to run WatchKit App on hardwareThis should be as simple as plugging the hardware into your MacBook (i.e. the iPhone that’s paired to the Apple Watch), selecting the correct device from the devices list, then running the App in the debugger. However, there are numerous pitfalls:

  • You need either a developer licence or a personal team set up. See Team | Identity in the Project settings
  • Xcode may think that the iPhone and Watch are unpaired – restarting Xcode solved this one for me, other people have had to re-boot their watch and/or phone
  • Xcode may not have the symbols for your Watch OS (this happened after I updated to Watch OS 2.1) – however, it seems happy to download them once you connect to the internet

Re-booting, re-connecting the phone to the MacBook, re-starting Xcode eventually sorted this out.
I’d already worked through a couple of tutorials for writing WatchKit apps, but you learn far more by writing your own.
Calc On Watch
The end result looks great, although the buttons are slightly too small for frequent use, even on a 42mm Apple Watch.

1 Comment

Filed under Programming, Swift

Keyboard handling in Swift for iOS App

swiftI’ve updated my hobby project to take keyboard input. This ought to be pretty simple, but I came across a few snags that stopped the user experience being as smooth as should be.

Simulator only presents the pop-up keyboard once

This has been bothering me for a while, I resorted to switching to a different simulator profile (e.g. iPhone 4s / iPhone 5). It turns out that, by typing into the laptop keyboard instead of tapping the UI keyboard, the switch to hardware keyboard was semi-permanent. As per this StackOverflow page, you can restore the keyboard by in the Similar by Hardware -> Keyboard -> Toggle Software Keyboard (or ⌘K).

How to change the pop-up keyboard to ‘Done’

By default, the pop-up keyboard shows the enter/return key as “Return”. For some instances, you want to change that – this is as simple as changing the “Return Key” property on the text field in the story board:

How to dismiss keyboard when user presses return key

By default, the software keyboard does not disappear when you tap return (either on the hardware keyboard or on the software keyboard). There are several steps to achieve this, which are well discussed on StackOverflow. There are a couple of implementations choices for textFieldShouldReturn, this one worked for me:

    // UITextFieldDelegate implementation
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        return false

coupled with the change below for leaving the text field.

How to dismiss keyboard when user leaves the text field

Another obvious feature I wanted is to dismiss the keyboard if the user taps elsewhere in the App. The key here is to tell the view to recognise a tap (that is, UITapGestureRecognizer). See ‘Close iOS keyboard by touching anywhere’ on StackOverflow discussion.

Leave a comment

Filed under Programming, Swift

Tech Book: Swift for the Really Impatient, Matt Henderson & Dave Wood

SI love the title of this book, the authors kept the content as concise as possible and showed that it really is possible to give a decent introduction to a programming language in just 156 pages (and less than 1cm). The book is quite practical you can read it cover-to-cover to pick up the features of the language, then you can use the handy code snippets as a quick reference guide (and the index is pretty good for this too, not always the case).

I bought a 2015 edition, the only downside being that this seems to be aimed at Xcode 6 and is now slightly out of date. With Swift being an evolving language, that’s to be expected – some readers might prefer to work with the electronic copy and remain up to date.

It’s also worth mentioning that, if your aim is to write a simple iOS app in Swift, you might be better off working through a tutorial and learning Swift that way, along with picking up tips and tricks for working with Xcode. See FoodTracker and To Do.
Five Stars

Leave a comment

Filed under Programming, Swift, Tech Book