T1992
T1992

Reputation: 73

Change text of a label

I have a array that reads a .txt file and when you click a button the label changes in one of the words of the .txt file, but the label doen't change.

This is the code:

if(sender == self.button) {
    NSArray *words = [[NSArray alloc] initWithObjects:@"words.txt", nil];
    [randomLabel setText:[words objectAtIndex:random() % [words count]]];
}

What should I do so the label changes when I press the button? What file do I use?

Upvotes: 1

Views: 347

Answers (2)

WDUK
WDUK

Reputation: 19030

A few things here:

Reading in file into an array

Well, for starters you're not reading in the contents of the .txt file.

NSArray *words = [[NSArray alloc] initWithObjects:@"words.txt", nil];

This creates a 1 element array, with that one element being @"words.txt". I don't know the format of your .txt file, so I can't say for sure how you have to load it in. See How do I format a text file to be read in using arrayWithContentsOfFile on how to potentially do this.

Setting button text

Also, you need to make sure randomLabel actually refers to the label contained within the button, otherwise the button text won't change. Typically for a button, you'd change the title using the method:

- (void)setTitle:(NSString *)title forState:(UIControlState)state

So in your instance, it'd be:

NSString* newTitle = [words objectAtIndex:random() % [words count]];
[self.button setTitle:newTitle forState:UIControlStateNormal];

Is the code actually being called?

Double check that sender == self.button evaluates to true (for readability and clarity, I'd use [sender isEqual:self.button]). Use the debugger to step through the code, to see if that particular piece of code is being called. See http://mobile.tutsplus.com/tutorials/iphone/xcode-debugging_iphone-sdk/ on how to achieve this.

Upvotes: 2

Paramasivan Samuttiram
Paramasivan Samuttiram

Reputation: 3738

You should try using

  • (id)initWithContentsOfFile:(NSString *)aPath

Upvotes: 0

Related Questions