2017-03-16 45 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

相关问题