Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get WatchOS Digital Crown value

Tags:

swift

watchkit

I've been doing some research about making Apple Watch apps, but I'm having some trouble getting the value of the Digital Crown. I looked at the WKCrownSequencer but not sure what to do with it. Could someone show me how I would go about getting a variable with values 1-10 that change when you turn the Digital Crown. Thanks!

like image 476
PiedPiper Avatar asked Aug 17 '17 04:08

PiedPiper


2 Answers

You need to conform your InterfaceController subclass to WKCrownDelegate and implement the crownDidRotate method.

If you want your value to be between 1 and 10, you just need to implement some simple logic for checking what would the value be when you added the rotationalDelta and if it would be out of the range 1-10, map value to either 1 or 10, depending on which direction the new value would exceed. I have assumed you want value to be Int, if not, just remove the conversion of rotationalDelta to Int and value will be Double.

Keep in mind, that a rotationalDelta of 1.0 represents a full rotation of the crown and rotationalDelta changes its sign based on the direction of the rotation.

class MyInterfaceController: WKInterfaceController, WKCrownDelegate {
    var value = 1
    @IBOutlet var label: WKInterfaceLabel!

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)
        crownSequencer.delegate = self
    }

    func crownDidRotate(_ crownSequencer: WKCrownSequencer?, rotationalDelta: Double) {
        let newValue = value + Int(rotationalDelta)
        if newValue < 1 {
            value = 1
        } else if newValue > 10 {
            value = 10
        } else {
            value = newValue
        }
        label.setText("Current value: \(value)")
    }
}
like image 140
Dávid Pásztor Avatar answered Nov 15 '22 05:11

Dávid Pásztor


After watchOS 3

After watchOS3 it's possible to take value of Digital Crown. Check this documentation on Apple.

Basically you need to use WKCrownDelegate in your View Controller. An example code will something like this:

- (void)willActivate {
    [super willActivate];
    self.crownSequencer.delegate = self;
    [self.crownSequencer focus];
}

- (void)crownDidRotate:(WKCrownSequencer *)crownSequencer rotationalDelta:(double)rotationalDelta {
    self.totalDelta = self.totalDelta + rotationalDelta;
    [self updateLabel];
}

- (void)updateLabel {
    [self.label setText:[NSString stringWithFormat:@"%f", self.totalDelta]];
}

What is rotationalDelta

A value of 1.0 appears to indicate that the crown has completed a full rotation.

Warning

Please don't use this code directly, it's just an example. Check documentation from Apple's site first.

like image 35
mgyky Avatar answered Nov 15 '22 03:11

mgyky