如何在故事板中的标签中显示NSArray?

时间:2014-08-11 05:12:37

标签: xcode storyboard nsarray label viewcontroller

我对编程非常陌生,并且在弄清楚如何使用xcode方面遇到了很多麻烦。我试图连接一个NSArray(其中包含各种问题并将以随机顺序显示这些问题)到我在故事板中的一个ViewControllers上的标签中。我已经搜索过并尝试过,似乎无法得到它。任何人都可以帮我搞清楚吗?我觉得很容易,我只是错过了一些东西。

1 个答案:

答案 0 :(得分:1)

好的。这是你做的:

1)声明事情......

@interface ViewController ()
{
    NSArray *questionArray;
    UILabel *questionLabel;
}

@end

2)ViewDidLoad:

- (void)viewDidLoad
{
    [super viewDidLoad];
    //create question array
    questionArray = [NSArray arrayWithObjects:@"Question 1?", @"Question 2?", @"Question 3?", @"Question 4?", nil];

    //random a question
    int lowerBound = 0;
    int upperBound = [questionArray count] - 1;
    int randomValue = lowerBound + arc4random() % (upperBound - lowerBound);

    //create UILabel
    questionLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 20)];
    [questionLabel setTextAlignment:NSTextAlignmentCenter];
    [questionLabel setText:[questionArray objectAtIndex:randomValue]];
    [self.view addSubview:questionLabel];

    //create next button
    nextButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 150, 320, 100)];
    [nextButton setTitle:@"Next Question" forState:UIControlStateNormal];
    [nextButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(nextQuestionButtonSelected) forControlEvents:UIControlEventTouchUpInside];
}

3)点击按钮时

//Create action connection in the storyboard..
- (IBAction)nextQuestionButtonClicked:(id)sender
{
    //random a question again
    int lowerBound = 0;
    int upperBound = [questionArray count] - 1;
    int randomValue = lowerBound + arc4random() % (upperBound - lowerBound);

    [questionLabel setText:[questionArray objectAtIndex:randomValue]];
}