今天换书到IOS programming The Big Nerd Ranch Guide (4th Edition)
源码位置:https://github.com/ianzhengnan/Quiz
第一章:Quiz
它使用xib文件做为user interface。 通过一个简单的例子讲解了ios开发的基本步骤和方法。
涉及知识点:
1. xib文件: 它是ios7以前人们经常使用的一种user interface,现在新的IOS开发人员比较多的使用storyboard
它们都是用xml文件的形式组织UI。
2. MVC: 又谈到它了,每本书必谈。 这本书通过一副图形象的描述了它。很直观。
3. outlet, action: 创建ViewController 和 UI上控件的关联。两种方式:一种,直接拖动连接。一种:先创建相应的实例变量和方法,然后拖动。
效果:
实现步骤:
1. 新建项目,选择single view application. 因为我用的是xcode6.1.1。这里不能创建一个空的工程。
2. 新建一个xib文件命名为ViewController.xib。 它是我们的Root controller。后面会说怎么设置。
3. 拖动两个lable和两个button控件到xib中的view内。
4. ViewController.m文件中键入如下代码:
@property (nonatomic, weak) IBOutlet UILabel *questionLable;
@property (nonatomic, weak) IBOutlet UILabel *answerLable;
- (IBAction)showQuestion:(id)sender { }
- (IBAction)showAnswer:(id)sender { }
5. 建立关联
选中ViewController.xib文件中的File's owner,然后在其属性面板中键入ViewController设置它的控制器
然后在file's owner上面点右键或者ctrl+左键可以弹开关联对话框。在此对话框中拖动questionLable到UI上的questionLable上。同样的answerLable也做好关联。
还要记得对view做关联。
最后关联button到两个IBAction方法上。
6. 创建模型。
这里的模型是连个数组。
还有一个计数器
@property (nonatomic) int currentQuestionIndex;
@property (nonatomic, copy) NSArray *questions;
@property (nonatomic, copy) NSArray *answers;
7. 在ViewController.m文件中添加方法initWithNibName
这个方法是在屏幕加载完后调用。在这里我们将初始化我们的model
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self){
self.questions = @[@"From what is cognac made?",
@"What is 7 + 7?",
@"What is the captical of Vermont?"];
self.answers = @[@"Grapes",
@"14",
@"Montpelier"];
}
return self;
}
8. 实现两个按钮点击方法
- (IBAction)showQuestion:(id)sender {
self.currentQuestionIndex++;
if (self.currentQuestionIndex == [_questions count]) {
self.currentQuestionIndex = 0;
}
self.questionLable.text = self.questions[self.currentQuestionIndex];
self.answerLable.text = @"???";
}
- (IBAction)showAnswer:(id)sender {
self.answerLable.text = self.answers[self.currentQuestionIndex];
}
9. 创建ViewController的实例,并把它设为Root controller.
在AppDelegate.m文件中的didFinishLaunchingWithOptions方法内添加
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
ViewController *quizVC = [[ViewController alloc] init];
self.window.rootViewController = quizVC;
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
9. 运行程序