【UI初级 连载二】------做一个100秒倒计时的程序,注意考虑,当程序进入后台时的情况。

    /*
    
做一个100秒倒计时的程序,注意考虑,当程序进入后台时的情况。
     */

   

AppDelegate.h文件中:
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

{
   
UILabel *_label;
   
NSInteger _index;
   
NSTimer *_timer;
   
NSDate *_backgroundDate;
}

@property (strong, nonatomic) UIWindow *window;

@end

AppDelegate.m文件中:
#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (
BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   
// Override point for customization after application launch.

   
//******* 创建window窗口 *********************
   
//拿到屏幕的大小
   
CGRect rect = [UIScreen mainScreen].bounds;
   
//创建一个window
   
self.window = [[UIWindow alloc]initWithFrame:rect];
   
//设置窗口颜色
   
self.window.backgroundColor = [UIColor greenColor];
   
//把当前的window作为程序的主window显示出来
    [
self.window makeKeyAndVisible];
   
   
_index = 100;
   
//创建一个label
    
_label = [[UILabel alloc]initWithFrame:CGRectMake(0, 175, 375, 75)];
   
//设置label背景色
   
_label.backgroundColor = [UIColor grayColor];
   
_label.text = @"100";
   
//设置文字颜色
   
_label.textColor = [UIColor whiteColor];
   
//设置文字对齐方式
   
_label.textAlignment = NSTextAlignmentCenter;
   
//设置字体大小
   
_label.font = [UIFont boldSystemFontOfSize:24];
   
   
   
//label添加到window
    [
self.window addSubview:_label];
   
   
_timer = [NSTimer scheduledTimerWithTimeInterval:1
                                             
target:self
                                           
selector:@selector(timeAction:)
                                           
userInfo:nil repeats:YES];
   
   
return YES;
}

- (
void)timeAction:(NSTimer *)timer{

    
_index --;
   
_label.text = [NSString stringWithFormat:@"%ld",_index];;
   
if (_index == 0) {
        [timer
invalidate];
       
return;
    }
}

//程序已经进入后台
- (
void)applicationDidEnterBackground:(UIApplication *)application {
    [
_timer invalidate];//停止计时器
   
_backgroundDate = [NSDate date];//获得程序进入前台时的时间
}
//程序将要进入前台
- (
void)applicationWillEnterForeground:(UIApplication *)application {
   
NSDate *foregroundDate = [NSDate date];//获得程序即将进入活动状态时的时间
   
NSTimeInterval subTime = [foregroundDate timeIntervalSinceDate:_backgroundDate];//获得程序待在后台的时间
   
_index -= subTime;
   
_label.text = [NSString stringWithFormat:@"%ld",_index];
    [
NSTimer scheduledTimerWithTimeInterval:1
                                    
target:self
                                  
selector:@selector(timeAction:)
                                  
userInfo:nil
                                   
repeats:YES];
}
@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值