iPhoneダイアル6

数字の6がくるっと回る。というiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@interface ViewController ()

@property (nonatomic, weak) UIView *six;

@property (nonatomic) NSUInteger counter;

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor brownColor];

    

    

    [self create6:[UIColor lightGrayColor]];

    

    [self createDial];

    

    self.six = [self create6:[UIColor whiteColor]];

}

– (UIView *)create6:(UIColor *)color

{

    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(10, 80, 300, 300)];

    v.backgroundColor = [UIColor clearColor];

    [self.view addSubview:v];

    

    float r1 = 300.0 / 3.0;

    UIView *circle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, r1, r1)];

    circle.layer.cornerRadius = r1/2.0;

    circle.backgroundColor = color;

    circle.center = CGPointMake(150, 150);

    [v addSubview:circle];

    

    UIView *bar = [[UIView alloc] initWithFrame:CGRectMake(100, 40, 30, 120)];

    bar.layer.cornerRadius = 15;

    bar.backgroundColor = circle.backgroundColor;

    [v addSubview:bar];

    float r2 = 300 / 7.2;

    UIView *hole = [[UIView alloc] initWithFrame:CGRectMake(0, 0, r2, r2)];

    hole.center = circle.center;

    hole.backgroundColor = self.view.backgroundColor;

    hole.layer.cornerRadius = r2/2.0;

    [v addSubview:hole];

    

    return v;

}

– (void)createDial

{

    CGPoint o = CGPointMake(160, 230);

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

        float angle = i * M_PI/3.0M_PI/6.0;

        float x = 110 * cos(angle) + o.x;

        float y = 110 * sin(angle) + o.y;

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

        l.text = [@(i+1) stringValue];

        l.font = [UIFont boldSystemFontOfSize:20];

        l.textColor = [UIColor whiteColor];

        [l sizeToFit];

        l.center = CGPointMake(x, y);

        l.backgroundColor = [UIColor clearColor];

        [self.view addSubview:l];

    }

}

#define mInterval 0.05

– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    [NSTimer scheduledTimerWithTimeInterval:mInterval target:self selector:@selector(tick:) userInfo:nil repeats:YES];

}

– (void)tick:(NSTimer *)sender

{

    self.counter++;

    float boundary = 6.0 / mInterval;

    if (self.counter > boundary) {

        [sender invalidate];

        self.counter = 0;

        return;

    }

    

    float dAngle = mInterval * M_PI/3.0;

    self.six.transform = CGAffineTransformRotate(self.six.transform, dAngle);

}

@end