I’m trying to create a simple Quiz app (I’m a beginner), when I launch the app I want a UILabel to show the first question (of an array of questions). I’m having some trouble with setting the initial value.
I’ve done a couple of attempts, whiteout success. I my QuizAppDelegate.h file I declare my UILabel like this:
IBOutlet UILabel * questionField;
In my main .m file I have tried the following:
- (id)init {
[super init];
questions = [[NSMutableArray alloc] init];
// Not working
questionField = [[UILabel alloc] init];
[questionField setText:@"Hello"];
// Working
NSLog(@"Hello");
[self defaultQuestions];
// [self showQuestion];
return self;
}
Another thing I have tried is the following in QuizAppDelegate:
@property (nonatomic, retain) IBOutlet UILabel *questionField;
- (void)changeTitle:(NSString *)toName;
And in the .m file:
@synthesize questionField;
- (id)init {
[super init];
questions = [[NSMutableArray alloc] init];
// Not working
[self changeTitle:@"Hello"];
// Working
NSLog(@"Hello");
[self defaultQuestions];
// [self showQuestion];
return self;
}
-(void)changeTitle:(NSString *)toName {
[questionField setText:toName];
}
Any tips on how to solve this would be great!
// Anders
Hopefully you’re not actually putting code into
main.m. On iOS, you rarely modify that file.Since you’re doing everything in the AppDelegate, let’s keep it there (as opposed to creating a new
UIViewController). Let’s start with the basics.Adding the Label as an instance variable
You’re doing this correctly—inside the curly braces of the
.hfile, put the lineThen, declare the corresponding property, and make sure to synthesize it in the
.mfile.Adding the UILabel in Interface Builder
Open up
MainWindow.xib. Drag a UILabel from the Library to the Window that represents your app’s window. Then Control-Drag from the AppDelegate object (the third icon on the left in Xcode 4; it’ll be labelled in the Document window in IB 3). You’ll see a little black window come up—select the option calledquestionFieldto make the connection.See this link for screenshots and how to make connections in IB. The same applies in Xcode 4.
Changing the text
You don’t need a separate method to change the text—just modify the label’s
textproperty.Pick a method that’ll be called when the app launches (
applicationDidFinishLaunching:WithOptions:is a good place to do it in), and put the following code:And that’s it!
Code
QuizAppDelegate.h
QuizAppDelegate.m