Sipa
Sipa

Reputation: 383

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

I have a text file of words and i make it to read in my project its fine, now i want to split words strings in half and show randomly on multiple labels which i make on my view.

    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);

I make 5 labels how can i make my text file words to split and appear randomly on these five labels?

Upvotes: 1

Views: 155

Answers (2)

Sipa
Sipa

Reputation: 383

AS -Sergey recommend half of my problem solved i am able to show a word string of text file on label. remove this labels[i].text from code and call

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];


}

This shows a full string of word now i want to split a word string in two parts for example if i have a word Apple it should be split in as App and le and show it randomly appear on different labels any help appreciated.

Upvotes: 1

Sergey
Sergey

Reputation: 1617

You can try to use this

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

Upvotes: 1

Related Questions