落書き – なぞると波のように動くフォント

UILabelをスワイプ or Tapで波の様に動かしてみる

(XcodeのiOS6 Simulatorで試しています)

ポイント

・NSStringを一文字ずつUILabelにバラす (NSRangeとforループ)

・touchBeginとmoveで指が上にきたViewを動かす

サンプルコード

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    

    NSString *str = @”made in japan”;

    

    // NSStringを1文字にばらして UILabelにする

    CGPoint point = CGPointMake(40, 120);

    for (int i=0; i<[str length]; i++) {

        NSRange range = NSMakeRange(i, 1);

        NSString *c = [str substringWithRange:range];

        

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

        l.backgroundColor = [UIColor clearColor];

        l.font = [UIFont fontWithName:@”Chalkduster” size:25];

        l.text = c;

        

        // 文字のサイズでxの幅を決めていく

        [l sizeToFit];

        point = CGPointMake(point.x + l.bounds.size.width, point.y);

        l.center = point;

        [self.view addSubview:l];

    }

}

// タッチ or スワイプしたところがラベルの場合、跳ねさせる

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

{

    UITouch *t = [touches anyObject];

    CGPoint p = [t locationInView:self.view];

    [self waveFont:p];

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

{

    UITouch *t = [touches anyObject];

    CGPoint p = [t locationInView:self.view];

    [self waveFont:p];

}

// Viewのステータス用

#define Move 1

#define Stop 0

// 指定の座標にラベルがあった場合ぴょんと飛ばす

– (void)waveFont:(CGPoint)p

{

    for (UIView *v in self.view.subviews) {

        if ([v isKindOfClass:[UILabel class]]

            && CGRectContainsPoint(v.frame, p)) {

            if (v.tag == Stop) {

                v.tag = Move;

                [UIView animateWithDuration:0.5 animations:^{

                    v.center = CGPointMake(v.center.x, v.center.y80);

                } completion:^(BOOL finished) {

                    [UIView animateWithDuration:0.5 animations:^{

                        v.center = CGPointMake(v.center.x, v.center.y + 80);

                        v.tag = Stop;

                    }];

                }];

            }

            

        }

    }

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

← 過去の投稿へ

次の投稿へ →

2件のコメント

  1. いつも拝見しております。

  2. ありがとうございます!