Shane Hou
Shane Hou

Reputation: 5028

How to make an animated button in Apple WatchKit?

I'd like to make a button with animation in WatchKit, but it seems I can't find a way to modify WKInterfaceButton or drag an image into button in storyboard. Any help is appreciated.

Upvotes: 7

Views: 5488

Answers (2)

DenVog
DenVog

Reputation: 4286

Reck's post worked for me in instances that I needed to control the repeat count or duration. If you simply want to start or stop an animation for a button, the following works for me, where twoButton is a WKInterfaceButton and I have a set of images name [email protected], [email protected], etc.

- (void)startButtonAnimating
{
    // This works, but can't control repeat counts or duration
    [self.twoButton setBackgroundImageNamed:@"Bus"];
    // But you can stop after a delay by setting background image nil
    [self performSelector:@selector(stopGroupButtonAnimating) withObject:nil afterDelay:1.5];
}

- (void)stopButtonAnimating
{
    [self.twoButton setBackgroundImage:nil];
}

Upvotes: 1

Shane Hou
Shane Hou

Reputation: 5028

After some research I found the solution, it's pretty simple but easily ignored :)

First, drag a button into a scene created in storyboard.

Second, select button, modify its property content from Text to Group. If you can't find content property, click the Attributes Inspector button at top right of your screen, it looks like a breakpoint button or a down arrow with a bar.

enter image description here

Now you can control group created inside your button. You need to add a reference of this WKInterfaceGroup inside your controller code. Here is an example:

@interface AAPLButtonDetailController()
@property (weak, nonatomic) IBOutlet WKInterfaceGroup *buttonGroup;   
@end


@implementation AAPLButtonDetailController

- (instancetype)init {
    self = [super init];

    if (self) {
        // Initialize variables here.
        // Configure interface objects here.
        [_buttonGroup setBackgroundImageNamed:@"Bus"];
        [_buttonGroup startAnimating];
    }

    return self;
}

So the button animation will be played after scene initialized. Remember only frame animation is supported for now, all frames in one animation should be named like "Bus0.png", "Bus1.png"....

enter image description here

Hope this can help :)

Upvotes: 20

Related Questions