1 // 2 // ViewController.m 3 // 飞舞的UIView 4 // 5 // Created by 大欢 on 16/1/18. 6 // Copyright © 2016年 bjsxt. All rights reserved. 7 // 8 /********************************************************/ 9 #import "ViewController.h" 10 11 #define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width 12 #define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height 13 14 //以小写k打头定义标示符 只作用于一个编译单元 15 16 //所有字母大写 作用于全局 17 18 @interface ViewController () 19 @property (nonatomic, strong) UIView * flyView; 20 @end 21 22 @implementation ViewController 23 24 - (void)viewDidLoad { 25 [super viewDidLoad]; 26 [self.view addSubview:self.flyView]; 27 28 NSTimer * timer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(flyAction) userInfo:nil repeats:YES]; 29 [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; 30 31 // [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(flyAction) userInfo:nil repeats:YES]; 32 } 33 34 - (void)flyAction { 35 36 CGRect rect = self.flyView.frame; 37 38 static int X = 1; 39 static int Y = 1; 40 41 if (rect.origin.x < 0 || rect.origin.x + rect.size.width > SCREEN_WIDTH) { 42 X *= -1; 43 } 44 if (rect.origin.y < 20 || rect.origin.y + rect.size.height > SCREEN_HEIGHT) { 45 Y *= -1; 46 } 47 48 rect.origin.x += X; 49 rect.origin.y += Y; 50 51 self.flyView.frame = rect; 52 53 } 54 55 - (UIView *)flyView { 56 57 if (!_flyView) { 58 _flyView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, 50, 50)]; 59 _flyView.backgroundColor = [UIColor orangeColor]; 60 } 61 return _flyView; 62 } 63 @end
/**************************************************************/