How to use WKCrownDelegate in WatchOS Development
Playing with Apple Watch's digital crowd
Table of contents
No headings in the article.
Hi everyone.
While working on a WatchOS application recently I needed to perform some operations in the application when the user rotated the digital crown; I had difficulties finding the solution because there were very few resources on the subject, and the official documentation is not clear enough for me. (A full example is always better). After doing some research on the subject, I finally was able to find a solution and this guide will explain step by step how I achieved it.
So I'm using Swift 5 on XCode 12.4 with WatchKit.
We gonna start from a blank project so it's clear for everybody:
The InterfaceController
code looks like this:
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
override func awake(withContext context: Any?) {
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
}
}
The first step will be to modify our InterfaceController so it conforms to WKCrownDelegate
protocol. This looks like this:
extension InterfaceController : WKCrownDelegate {}
Before implementing our protocol methods, we will need to add some code to our InterfaceController
class; we need to tell the crownSequencer it should focus, and define a delete. To do that, add a didAppear()
method (this method is automatically called when the watch interface is visible to the user). This looks like this:
override func didAppear() {
super.didAppear()
crownSequencer.delegate = self
crownSequencer.focus()
}
Now we are ready to listen to events; the available ones are :
func crownDidRotate(WKCrownSequencer?, rotationalDelta: Double)
Called when the user rotates the crown.
func crownDidBecomeIdle(WKCrownSequencer?)
Called when the user stops rotating the crown.
Full code:
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
override func awake(withContext context: Any?) {
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
}
override func didAppear() {
super.didAppear()
crownSequencer.delegate = self
crownSequencer.focus()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
}
}
extension InterfaceController : WKCrownDelegate {
func crownDidRotate(_ crownSequencer: WKCrownSequencer?, rotationalDelta: Double) {
print(rotationalDelta)
}
}
When the digital crown will rotate, the rotational delta will be printed like on the screenshot below :
I hope this article has helped you, feel free to add your suggestions in comments.
Thanks for reading.