iPhoneアドベントカレンダー

アドベントカレンダーという一日一個開けていいプレゼントの箱みたいなやつが気になる。そんな感じで、タップするとその日のプレゼントが出てくるようなiPhoneアプリのサンプルコードを描いてみます。

今回使った画像


動かすとこんな感じです

サンプルコード

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

    self.view.backgroundColor = [UIColor colorWithRed:0 green:0.3 blue:0 alpha:1.0];

    [super viewDidLoad];

    [self createCalendar];

}

– (void)createCalendar

{

    for ( int i=0; i<25; i++) {

        float x = (i%5) * 60 + 12.5;

        float y = (i/5) * 60 + 50;

        float size = 56;

        UIView *box = [[UIView alloc] initWithFrame:CGRectMake(x, y, size, size)];

        box.tag = i + 1;

        box.backgroundColor = [UIColor brownColor];

        [self.view addSubview:box];

        

        UILabel *day = [[UILabel alloc] init];

        [box addSubview:day];

        

        NSMutableAttributedString *mst = [[NSMutableAttributedString alloc] initWithString:[@(i + 1) stringValue]];

        [mst addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@”Futura-CondensedExtraBold” size:30], NSStrokeWidthAttributeName : @-7, NSStrokeColorAttributeName : [UIColor whiteColor], NSForegroundColorAttributeName : [UIColor brownColor],

                             } range:NSMakeRange(0, mst.length)];

        day.attributedText = mst;

        [day sizeToFit];

        day.center = CGPointMake(size/2.0, size/2.0);

        

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

        [box addGestureRecognizer:tap];

    }

}

– (void)openBox:(UITapGestureRecognizer*)gr

{

    CALayer *mask = [CALayer layer];

    UIImage *presentMask = [UIImage imageNamed:@”present”];

    mask.contents = (id)presentMask.CGImage;

    mask.frame = (CGRect){.size = CGSizeMake(46, 46)};

    

    UIView *present = [[UIView alloc] initWithFrame:CGRectMake(5, 5, 46, 46)];

    float hue = (arc4random() % 8) * 0.1 + 0.1;

    present.backgroundColor = [UIColor colorWithHue:hue saturation:0.7 brightness:1.0 alpha:1.0];

    present.layer.mask = mask;

    present.layer.masksToBounds = YES;

    

    [UIView transitionFromView:gr.view.subviews[0] toView:present duration:0.5 options:UIViewAnimationOptionTransitionFlipFromBottom completion:^(BOOL finished) {

        

    }];

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end