標籤:
1 #import "ViewController.h" 2 3 @interface ViewController () 4 { 5 UILabel *lable; 6 BOOL moveFlag; 7 NSInteger length; 8 UIButton *btn; 9 NSTimer *timer;10 }11 12 @end13 14 @implementation ViewController15 16 - (void)viewDidLoad {17 [super viewDidLoad];18 moveFlag = NO;19 length = 10;20 21 self.view.backgroundColor = [UIColor darkGrayColor];22 lable = [[UILabel alloc] init];23 lable.frame = CGRectMake(50, 100, 280, 50);24 lable.text = @"點我啊";25 lable.backgroundColor = [UIColor whiteColor];26 [self.view addSubview:lable];27 28 // 按鈕UIButton29 btn = [UIButton buttonWithType:UIButtonTypeCustom];30 // 設定按鈕座標、大小31 btn.frame = CGRectMake(170, 250, 50, 50);32 // 設定背景圖33 [btn setImage:[UIImage imageNamed:@"fire_down.png"] forState:UIControlStateNormal];34 [btn setImage:[UIImage imageNamed:@"blue_down.png"] forState:UIControlStateHighlighted];35 36 37 // 設定標題(狀態標題)38 // [btn setTitle:@"開始" forState:UIControlStateNormal];39 // [btn setTitle:@"按下" forState:UIControlStateHighlighted];40 41 // 給按鈕添加 [關聯事件]42 [btn addTarget:self action:@selector(touchMe) forControlEvents:UIControlEventTouchUpInside];43 // 添加背景色44 [btn setBackgroundColor:[UIColor cyanColor]];45 46 // 按鈕變圓47 btn.layer.cornerRadius = 20;48 // 添加按鈕到視圖上49 [self.view addSubview:btn];50 51 }52 53 -(void) touchMe54 {55 //判斷完了小球動沒有動56 if (moveFlag ==NO) {57 moveFlag = YES;58 }59 else60 moveFlag = NO;61 62 //當小球沒有動得時候,點小球-變動63 if (moveFlag) {64 timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(bollMove) userInfo:nil repeats:YES];65 [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];66 }67 else68 [timer invalidate];69 //當小球動得時候,點小球-不動70 71 }72 73 -(void) bollMove74 {75 76 if (btn.frame.origin.y>600) {77 length = -10;78 79 }80 else if (btn.frame.origin.y<0)81 {82 length = 10;83 }84 85 CGRect rect = btn.frame;86 rect.origin.y += length;87 btn.frame = rect;88 89 }
IOS UI-Button按鈕