对于 Xcode 5.0,我试图遵循 Big Nerd Ranch book第 2 版,似乎有点过时了。
有一个带有 2 个标签和 2 个按钮的测验项目示例。
我已经从书中复制了源代码,esp。 AppDelegate.h
:
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate> {
int currentQuestionIndex;
NSMutableArray *questions;
NSMutableArray *answers;
IBOutlet UILabel *questionField;
IBOutlet UILabel *answerField;
}
@property (strong, nonatomic) UIWindow *window;
- (IBAction)showQuestion:(id)sender;
- (IBAction)showAnswer:(id)sender;
@end
书中没有提到MainWindow.xib
,但我有一个Main.storyboard
,我在其中放置了标签和按钮:
我可以在源代码编辑器的左侧(在上面屏幕截图的中间)和“连接检查器”(例如“Touch Up Inside”)中看到 4 个空心小圆圈,但我就是不能'不要让他们联系起来。我尝试从小圆圈拖动并按住 Ctrl 键拖动到按钮/标签,有一条蓝线,但它没有连接。
当我右键单击按钮/标签时,会出现一个关于“Outlets”的灰色菜单,但那里没有列出我的 IBOutlets/IBActions。
请问如何给标签和按钮添加连接?
更新:
根据 Rob 的建议(谢谢 +1),我已将属性和方法移至 ViewController.*
并能够连接标签和按钮。单击按钮时,我看到正在调用的方法。
但是现在我遇到了 ViewController
类的 init
方法没有运行的问题,因此两个数组都是 nil。
请问还有什么提示吗?而且我不确定为什么关闭我的问题的建议“过于宽泛”——我附上了(简短的)代码和屏幕截图,我的 2 个问题非常具体(并且可能是基本的)。
ViewController.h:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
int currentQuestionIndex;
NSMutableArray *questions;
NSMutableArray *answers;
IBOutlet UILabel *questionField;
IBOutlet UILabel *answerField;
}
- (IBAction)showQuestion:(id)sender;
- (IBAction)showAnswer:(id)sender;
@end
ViewController.m:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (id)init { // XXX is never called??
self = [super init];
if(self) {
questions = [[NSMutableArray alloc] init];
answers = [[NSMutableArray alloc] init];
[questions addObject:@"What is 7 + 7?"];
[answers addObject:@"14"];
[questions addObject:@"What is the capital of Vermont?"];
[answers addObject:@"Montpelier"];
[questions addObject:@"From what is cognac made?"];
[answers addObject:@"Grapes"];
}
return self;
}
- (IBAction)showQuestion:(id)sender // XXX runs ok when clicked
{
currentQuestionIndex++;
if (currentQuestionIndex == [questions count]) {
currentQuestionIndex = 0;
}
NSString *question = [questions objectAtIndex:currentQuestionIndex];
NSLog(@"displaying question: %@", question);
[questionField setText:question];
[answerField setText:@"???"];
}
- (IBAction)showAnswer:(id)sender // XXX runs ok when clicked
{
NSString *answer = [answers objectAtIndex:currentQuestionIndex];
[answerField setText:answer];
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
最佳答案
您的 IBOutlet
引用应该在 View Controller 类中,而不是应用程序委托(delegate)类中。场景的基类(如您选择场景下方的栏后的“身份检查器”中所示)是 View Controller ,因此您的 IBOutlet
引用将与它相关联。当您控制从 Storyboard 拖动到 View Controller 类时,您会发现它会开始按照您的预期运行。
应用委托(delegate)旨在定义您的应用在启动、进入后台等时的行为。对于用户与应用交互时的行为,您通常将其放在 View Controller 类中。
关于ios - 在 Main.storyboard 和 AppDelegate.h 之间建立联系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19163626/