1

我有一个读取 .txt 文件的数组,当您单击按钮时,标签会在 .txt 文件的某个单词中发生变化,但标签不会改变。

这是代码:

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

当我按下按钮时,我应该怎么做才能改变标签?我使用什么文件?

4

2 回答 2

2

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.

于 2012-12-04T14:46:25.823 回答
0

你应该尝试使用

  • (id)initWithContentsOfFile:(NSString *)aPath
于 2012-12-04T14:46:17.667 回答