来自 Conway & Hillegass 的书“Big Nerd Ranch Guide, iOS Programming”,第 7 章“UIViewController”。
我们创建一个有两个视图的应用程序,两个 UIViewControllers。一个视图是我们在前几章中以编程方式创建和连接的 UIViewController,另一个视图我们应该在 xib 文件中创建并与文件所有者建立必要的连接。自定义视图应该显示一个标签和一个按钮。点击按钮后,标签应显示当前时间。
程序编译,但按下按钮后,标签不显示当前时间。我怀疑我的错误是在我需要在 xib 文件中设置与文件所有者的连接时。这是我所做的:我控制单击文件的所有者,选择“Received Actions: showCurrentTime”并将其拖到按钮上。然后选择:“结束时结束”。我控制单击文件的所有者,选择“Outlets:timeLabel”并将其拖到标签上。
任何人都可以发现错误吗?
这是代码:
TimeViewController.h:(自定义视图的UIViewController)
#import <Foundation/Foundation.h>
@interface TimeViewController : UIViewController
{
IBOutlet UILabel *timeLabel;
}-
(IBAction)showCurrentTime:(id)sender;
@end
时间视图控制器.m:
#import "TimeViewController.h"
@implementation TimeViewController
- (IBAction)showCurrentTime:(id)sender
{
NSDate *now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
[timeLabel setText:[formatter stringFromDate:now]];
}
@end
HypnoAppDelegate.m:
#import "HypnoAppDelegate.h"
#import "HypnosisViewController.h"
#import "TimeViewController.h"
@implementation HypnoAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//....creating an instance of our UIViewController and setting it as a root view. This is an instance of custom view we've created programmatically.
HypnosisViewController *hvc = [[HypnosisViewController alloc] init];
TimeViewController *tvc = [[TimeViewController alloc] init];
[[self window] setRootViewController:tvc];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
}
- (void)applicationWillTerminate:(UIApplication *)application
{
}
@end