iPhone 31 天的经典实例之Xcode4(第一篇 时钟练习)

这是一个简单的小应用,练习练习Lable控件的使用,和Timer定时器的功能。先看下效果图。下载见原文地址

http://www.leoshao.com/?p=46

1、创建view-based Application. 命名为MyClock

2、打开MyClockViewController.xib 调整背景色为黑色,拖入一个UILable控件

3、按住control把Lablel连接到MyClockViewController.h,代码如下<>

#import

@interface MyClockViewController : UIViewController {
UILabel
*clockLable;
}

@property (nonatomic, retain) IBOutlet UILabel
*clockLable;
-(void) updateLable;
@end

4、MyClockViewController.m文件内设置字体和实现updateLable操作

- (void)viewDidLoad
{
[clockLable setFont:[UIFont fontWithName:@"DBLCDTempBlack" size:64.0]];
[super viewDidLoad];
}

//更新lable为当前时间
-(void)updateLable{
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]init]autorelease];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *dateStr = [dateFormatter stringFromDate:[NSDate date]];
[clockLable setText:dateStr];
}

5、MyClockAppDelegate.h

#import
@class MyClockViewController;
@interface MyClockAppDelegate : NSObject
{
NSTimer *timer;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet MyClockViewController *viewController;
-(void) onTimer;
@end

6、MyClockAppDelegate.m设置计时器来执行updateLable

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
timer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
-(void) onTimer{
[self.viewController updateLable];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
[timer invalidate];
/*
Called when the application is about to terminate.
Save data if appropriate.
See also applicationDidEnterBackground:.
*/

}

- (void)dealloc
{
//[timer release];
[_window release];
[_viewController release];
[super dealloc];
}

注:刚知道timer是autorelease,所以dealloc就不能在release了。

posted on 2011-09-04 14:33  @Leo  阅读(864)  评论(0)    收藏  举报

导航