如何在 objective c 中的多个标签上显示文本文件中的随机词

How to show random words from a text file on multiple labels in objective c

我有一个文字文本文件,我让它在我的项目中阅读它很好,现在我想将文字字符串分成两半并随机显示在我在视图中制作的多个标签上。

    NSString *myfilePath = [[NSBundle mainBundle] pathForResource:@"textFile" ofType:@"txt"];

NSString *linesFromFile = [[NSString alloc]   initWithContentsOfFile:myfilePath encoding:NSUTF8StringEncoding error:nil];

myWords = [NSArray alloc];
myWords = [linesFromFile componentsSeparatedByString:@"\n"];

NSLog(@"%@", myWords);

我制作了 5 个标签,如何让我的文本文件单词拆分并随机出现在这五个标签上?

你可以试试这个

  NSMutableArray *words = [myWords mutableCopy];
  for (int i = 0; i<5 ;i++)
  {
    NSInteger index = arc4random()%words.count;
    labels[i].text = words[index];
    [words removeObjectAtIndex:index];
  }

AS -Sergey 建议我解决了一半的问题我能够在标签上显示文本文件的字符串。从代码中删除这个 labels[i].text 并调用

NSMutableArray<UILabel*>* labels = [NSMutableArray array];
NSMutableArray *words = [myWords mutableCopy];
for (int i = 0; i<5; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 70*i, 100, 40)];
    label.textColor = [UIColor whiteColor];
     //whatever other properties

    NSInteger index = arc4random()%words.count;
    label.text = words[index];
    [words removeObjectAtIndex:index];


    [self.view addSubview:label];
    [labels addObject: label];


}

这显示了一个完整的单词字符串,现在我想将一个单词字符串分成两部分,例如,如果我有一个单词 Apple,它应该被分成 App 和 le,并随机显示它出现在不同的标签上任何帮助赞赏。