【问题标题】:How to show random words from a text file on multiple labels in objective c如何在目标c中的多个标签上显示文本文件中的随机单词
【发布时间】:2017-03-16 12:40:48
【问题描述】:

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

    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 个标签,我怎样才能让我的文本文件单词拆分并随机出现在这五个标签上?

【问题讨论】:

  • 标签上的文字会随时间变化吗?如果不是,你怎么能在你的文本文件中显示你的全部文本。
  • 是的,它应该随机变化.....
  • 两个或多个标签可以同时显示相同的文字吗?
  • 是的,这就是问题所在..
  • 你的意思是不能同时显示相同的文字?

标签: ios objective-c nsstring


【解决方案1】:

你可以试试这个

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

【讨论】:

  • 读取对象 UILabel 的数组元素的方法是什么?
  • 什么意思?你说你已经有 5 个标签,所以你需要用这个标签创建数组,像这样:NSArray&lt;UILabel*&gt;* labels = @[label1,label2,label3,label4,label5];
  • 哦,我用循环创建了标签 for (int i = 1; i
  • 好的。在循环体中创建变量NSMutableArray&lt;UILabel*&gt;* labels = [NSMutableArray array]并调用[labels addObject: label]
  • 或者你可以在这个循环中填充文本。在你创建和配置标签之后,在循环之前添加这个NSMutableArray *words = [myWords mutableCopy];,在循环体中添加这个NSInteger index = arc4random()%words.count;label.text = words[index]; [words removeObjectAtIndex:index];
【解决方案2】:

AS -Sergey 建议我解决了一半的问题,我能够在标签上显示文本文件的单词字符串。从代码中删除这个标签[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 并显示它随机出现在不同的标签上,任何帮助表示赞赏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多