引き続き、iOS7で見た目が変わったからチャレンジ。今日は、UIAlertViewを使って、数の大きい、小さいを答えていくiPhoneアプリを描いてみます。
動作イメージ
XcodeからiOS7 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
@interface ViewController () <UIAlertViewDelegate>
@property (strong, nonatomic) NSMutableArray *points;
@property (strong, nonatomic) UIButton *button;
@property (nonatomic) int first;
@property (nonatomic) int second;
@property (nonatomic) int count;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
[self createPoints];
[self createNumber];
[self button];
}
– (void)createPoints
{
for (int i = 0; i<5; i++) {
float x = i * 20 + 200;
float y = 80;
UIView *point = [[UIView alloc] initWithFrame:CGRectMake(x, y, 10, 10)];
point.layer.cornerRadius = 5;
point.backgroundColor = [UIColor blackColor];
[self.view addSubview:point];
[self.points addObject:point];
}
}
– (void)createNumber
{
self.first = arc4random() % 10;
do {
self.second = arc4random() % 10;
} while (self.first == self.second);
}
– (void)show:(UIButton*)sender
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”More or Less” message:[NSString stringWithFormat:@”%d ? %d”, self.first, self.second] delegate:self cancelButtonTitle:@”cancel” otherButtonTitles:@”>”, @”<“, nil];
[alert show];
}
– (UIButton*)button
{
if (!_button) {
_button = [UIButton buttonWithType:UIButtonTypeCustom];
_button.frame = CGRectMake(100, 150, 110, 110);
_button.backgroundColor = [UIColor purpleColor];
_button.layer.cornerRadius = 55;
_button.titleLabel.font = [UIFont boldSystemFontOfSize:30];
[_button setTitle:@”try” forState:UIControlStateNormal];
[self.view addSubview:_button];
[_button addTarget:self action:@selector(show:) forControlEvents:UIControlEventTouchUpInside];
}
return _button;
}
– (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
BOOL correct = NO;
BOOL less = self.first < self.second;
if (!less && buttonIndex == 1) {
correct = YES;
} else if (less && buttonIndex == 2){
correct = YES;
}
if (correct) {
for (UIView *p in self.points) {
if (![p.backgroundColor isEqual:[UIColor yellowColor]]) {
p.backgroundColor = [UIColor yellowColor];
[UIView animateWithDuration:0.2 animations:^{
p.transform = CGAffineTransformMakeScale(3.0, 3.0);
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.6 animations:^{
p.transform = CGAffineTransformIdentity;
}];
}];
[self createNumber];
break;
}
}
}
}
– (NSMutableArray*)points
{
if (!_points) {
_points = [[NSMutableArray alloc] init];
}
return _points;
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end