萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 安卓開發 >> 在iOS中倒數計時的實例編程

在iOS中倒數計時的實例編程

想給你的iPhone計算離午夜12:00點的剩余時間嗎?看看小編為大家整理的在iOS中倒數計時的實例編程吧!

首先運行以安裝好的 xCode

選擇: File->New Project.

從 "New Project" 窗口

選擇 : iPhone OS ->Applications-> View-Based Application

命名 : 我這裡命名為 "minutesToMidnight"

(1)  在xCode打開 minutesToMidnightViewController.h 文件

#import

@interface minutesToMidnightViewController : UIViewController {

NSTimer *timer;

IBOutlet UILabel *countdownLabel;

}

@property(nonatomic,retain)  UILabel *countdownLabel;

@property (nonatomic, retain) NSTimer *timer;

-(void)onTimer;

@end

(2)  在xCode打開 minutesToMidnightViewController.m 文件

#import "minutesToMidnightViewController.h"

@implementation minutesToMidnightViewController

@synthesize timer;

@synthesize countdownLabel;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

[super viewDidLoad];

[countdownLabel setFont:[UIFont fontWithName:@"DBLCDTempBlack" size:128.0]];

countdownLabel.text = @"00:00:00";

self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(onTimer) userInfo:nil repeats: YES];

}

-(void)onTimer{

NSDate* now = [NSDate date];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit  | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now]; //

NSInteger hour = [dateComponents hour];

NSInteger min = [dateComponents minute];

NSInteger sec = [dateComponents second];

sec = 60 - sec;

min = 59 - min;

hour = 23 -  hour;

[gregorian release];

countdownLabel.text = [NSString stringWithFormat:@"%d:%d:%d", hour, min,sec];

}

- (void)didReceiveMemoryWarning {

// Releases the view if it doesn't have a superview.

[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.

}

- (void)viewDidUnload {

// Release any retained subviews of the main view.

// e.g. self.myOutlet = nil;

}

- (void)dealloc {

[super dealloc];

[timer release];

[countdownLabel release];

}

@end

完成後打開Interface Builder,進行UIView設置

(3) UIView 界面設置- 黑色背景,紅色字體,讓它看起來像一個鬧鐘。

雙擊文件: "MinutesToMidnightViewController.xib" ;

然後 "Interface Builder"  會自動打開,在這裡我們可以編輯改變界面

選擇: Tools -> Reveal In Document Window -> View

選擇:  Tools -> Attributes Inspector

在色條內選擇 "黑色",可以看到背景變為黑色

(4) 加入 UILabel 顯示我們的倒數時間

選擇: Tools -> Library ; 從Library顯示菜單中拖拉一個 Label 到 Main View

在主顯示上點擊 Label;從Label Attributes 上選著字體的顏色和字體大小。

(5)從 Interface Builder 寫入 UILabel 的 class file

再打開SDK工具 Interface Builder

在主視窗口或文件窗口;點擊 Label

選擇: Tools -> Connection Inspector

移動鼠標在"New Referencing Outlet" 後面圓圈上; 圓圈變為(+); 拖向直線連接到"File's Owner";

放開鼠標選擇鍵出現 "countdownLabel"; 選上它。

選擇: File -> Save then close Interface Builde

最後在 xCode 選擇 Build->Build and Go

以上就是小編為大家整理的在iOS中倒數計時的實例編程,希望對大家有所幫助。

 

copyright © 萬盛學電腦網 all rights reserved