iPhoneボタンメニュー

ボタンを押すと、そこまでピカピカするだけ、そんな感じのiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@interface ViewController ()

@property (nonatomic, weak) UIView *selected;

@end

@implementation ViewController

– (void)viewDidAppear:(BOOL)animated

{

    self.view.backgroundColor = [UIColor darkGrayColor];

    [self createRoundMenu];

}

– (void)createRoundMenu

{

    NSString *word = @”abcdefghijklmnopqrstuvwxyz”;

    for (int i=0; i<word.length; i++) {

        float x = (i % 10) * 45 + 35;

        float y = (i / 10) * 60 + 100;

        

        UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];

        l.tag = i + 1;

        l.text = [word substringWithRange:NSMakeRange(i, 1)];

        l.font = [UIFont boldSystemFontOfSize:30];

        l.textColor = [UIColor whiteColor];

        l.textAlignment = NSTextAlignmentCenter;

        l.center = CGPointMake(x, y);

        l.layer.masksToBounds = YES;

        l.layer.cornerRadius = 20;

        l.layer.borderWidth = 4;

        l.layer.borderColor = [UIColor lightGrayColor].CGColor;

        l.backgroundColor = [UIColor blackColor];

        [self.view addSubview:l];

        

        l.userInteractionEnabled = YES;

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];

        [l addGestureRecognizer:tap];

    }

}

– (void)tap:(UITapGestureRecognizer *)gr

{

    if (!self.selected) {

        self.selected = gr.view;

        gr.view.layer.borderColor = [UIColor whiteColor].CGColor;

        return;

    }

    

    BOOL asc = self.selected.tag < gr.view.tag;

    int start = self.selected.tag;

    int goal = gr.view.tag;

    

    self.selected = gr.view;

    

    if (asc) { 

        for (int i=start; i<=goal; i++)

            [self selectAnimation:i after:(i-start)*0.3 finish:(i == goal)];

    } else {

        for (int i=start; i>=goal; i–)

            [self selectAnimation:i after:(start-i)*0.3 finish:(i == goal)];

    }

}

– (void)selectAnimation:(int)tag after:(float)after finish:(BOOL)finish

{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(after * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        UIView *v = [self.view viewWithTag:tag];

        v.layer.borderColor = [UIColor whiteColor].CGColor;

        v.alpha = 0.3;

        [UIView animateWithDuration:0.3 animations:^{

            v.alpha = 1.0;

        } completion:^(BOOL finished) {

            if (!finish) {

                v.layer.borderColor = [UIColor lightGrayColor].CGColor;

            }

        }];

    });

}

@end