How can I show a sequence of buttons highlighting?

為{幸葍}努か 提交于 2020-01-01 20:36:12

问题


Similar to the Simon games of old, I want to show the user a button sequence & then have them repeat it back. The place I'm stuck is showing the first button highlighted for, say, 500ms, waiting 100ms, showing the second highlighted for 500ms, waiting another 100ms, showing the 3rd & so on.

From other Stackoverflower'ers I've gotten to this block:

redButton.highlighted = YES;

[UIView beginAnimations:@"" context:nil];
[UIView setAnimationStartDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[UIView setAnimationsEnabled:NO];
redButton.highlighted = NO;
[UIView commitAnimations];

[UIView beginAnimations:@"" context:nil];
[UIView setAnimationStartDate: [NSDate dateWithTimeIntervalSinceNow:2]];
[UIView setAnimationsEnabled:NO];
blueButton.highlighted = YES;
[UIView commitAnimations];

The redButton will highlight, but none of the subsequent actions take place.


回答1:


There might be a way to do this with Core Animation, but it is not necessary. You are not animating the highlighted property, you are just switching it on and off.

I created a simple view-based iPhone application to do this with timers. Here is the code from the view controller:

SimonTestViewController.h:

#import <UIKit/UIKit.h>

@interface SimonTestViewController : UIViewController {
 IBOutlet UIButton *redButton;
 IBOutlet UIButton *blueButton;
 IBOutlet UIButton *greenButton;
 IBOutlet UIButton *yellowButton;
}

- (void)highlightButton:(UIButton*)button Delay:(double)delay;
- (void)highlightOn:(NSTimer*)timer;
- (void)highlightOff:(NSTimer*)timer;

@end

SimonTestViewController.m:

#import "SimonTestViewController.h"

@implementation SimonTestViewController

const double HIGHLIGHT_SECONDS = 0.5; // 500 ms
const double NEXT_SECONDS = 0.6; // 600 ms

- (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];

 [self highlightButton:redButton Delay:0.0];
 [self highlightButton:blueButton Delay:NEXT_SECONDS];
 [self highlightButton:greenButton Delay:NEXT_SECONDS * 2];
 [self highlightButton:blueButton Delay:NEXT_SECONDS * 3];
 [self highlightButton:yellowButton Delay:NEXT_SECONDS * 4];
 [self highlightButton:redButton Delay:NEXT_SECONDS * 5];
}

- (void)highlightButton:(UIButton*)button Delay:(double)delay {
 [NSTimer scheduledTimerWithTimeInterval:delay target:self selector:@selector(highlightOn:) userInfo:button repeats:NO];
}

- (void)highlightOn:(NSTimer*)timer {
 UIButton *button = (UIButton*)[timer userInfo];

 button.highlighted = YES;

 [NSTimer scheduledTimerWithTimeInterval:HIGHLIGHT_SECONDS target:self selector:@selector(highlightOff:) userInfo:button repeats:NO];
}

- (void)highlightOff:(NSTimer*)timer {
 UIButton *button = (UIButton*)[timer userInfo];

 button.highlighted = NO;
}


来源:https://stackoverflow.com/questions/1672060/how-can-i-show-a-sequence-of-buttons-highlighting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!