2017-03-16 16 views
1

我有一個單詞文本文件,我讓它在我的項目中讀取它的罰款,現在我想分開一半字串和隨機顯示在我看來,我製作了多個標籤。如何從目標中的多個標籤上的文本文件中顯示隨機單詞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個標籤我如何讓我的文本文件單詞分裂並隨機出現在這五個標籤上?

+0

做的標籤上的文字會改變每個時間框?如果不是,你怎麼能在你的文本文件中顯示你的整個文本。 – aircraft

+0

是的,它應該隨機更改..... – Sipa

+0

可以同時顯示兩個標籤或更多文本? – aircraft

回答

1

。從代碼中刪除該標籤[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]; 


} 

這說明詞的完整字符串現在我想分兩個部分,例如分割一個字串,如果我有一個字蘋果應該在拆分作爲應用程序和樂,並顯示它隨機出現在不同的標籤任何幫助讚賞。

1

你可以試試AS -Sergey推薦我的問題解決了一半,我能夠顯示文本文件的標籤上的文字字符串使用此

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

什麼將讀取對象UILabel的數組元素的方法? – Sipa

+0

你的意思是?你說你已經有5個標籤了,所以你需要用這個標籤創建一個數組,例如:NSArray * labels = @ [label1,label2,label3,label4,label5];' – Sergey

+0

哦,我用循環創建了標籤for(int i = 1; i <5; i ++){UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(30,70 * i,100,40)]; label.textColor = [UIColor whiteColor]; label.backgroundColor = [UIColor greenColor]; } – Sipa

相關問題