【问题标题】:How to display an NSArray in a label in a storyboard?如何在情节提要的标签中显示 NSArray?
【发布时间】:2023-03-14 14:56:01
【问题描述】:

我真的是编程新手,在弄清楚如何使用 xcode 时遇到了很多麻烦。我试图将一个 NSArray(其中包含各种问题并将以随机顺序显示这些问题)连接到我在情节提要中的一个 ViewController 上的标签。我已经搜索并尝试过,但似乎无法得到它。谁能帮我弄清楚?我觉得它真的很容易我只是错过了一些东西。

【问题讨论】:

  • 您想只显示其中一个数组项的文本,还是全部显示?如果您希望它随机显示一个,您可能希望在运行时设置标签的文本,而不是通过在 Xcode 中建立连接。你可以将它绑定到一个数组控制器,但这可能比仅仅设置文本来响应应该触发它的任何事件更复杂。
  • 不,我需要所有这些。我想要做的是从列表中选择一个问题并显示在标签中,以便当用户移动到下一个问题时,从列表中随机选择另一个问题并显示。基本上我需要它,以便顺序不是预先选择的,而是随机的(又名 NSArray 是随机的),并链接到将显示它的按钮。也感谢您花时间回复:)

标签: xcode storyboard nsarray label viewcontroller


【解决方案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]];
}

【讨论】:

  • 谢谢!只有一件事:(除了按钮我得到一个错误之外,一切正常。在“[nextButton addTarget:self action:@selector(nextQuestionButtonSelected) forControlEvents:UIControlEventTouchUpInside];”行中,我得到一个错误“未声明的扇区” nextQuestionButtonSelected" ".
  • @Matt 这只是一个警告,没什么大不了的!删除该行。我忘记了它,它什么也没做。完成工作的方法是nextQuestionButtonClicked
  • 哦,我意识到我将按钮连接到了错误的 IBAction!我的错。无论如何,谢谢你现在工作正常:D
  • 很抱歉再次打扰您@Ty_,但我有什么办法可以让这个标签只针对一个情节提要而不会出现在多个情节提要上? (只是标签 bc 我更改了它,以便我有多个情节提要,因此当我单击下一个问题时,它只会转到下一个情节提要,该情节具有相同的标签,从 questionArray 中随机选择一个问题。基本上我的问题是标签仍在显示例如,不需要像“选择难度”这样的标签的情节提要
  • @Matt 我想帮助 Mat。但我不明白你想要完成什么……你能不能再发一个问题,并清楚地问你想要什么。请附上storyboardscode 的屏幕截图。我会尽力回答你的问题。
猜你喜欢
  • 1970-01-01
  • 2012-07-05
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多