2013-08-27 116 views
1

我從NSMutableArray動態創建標籤。在創建標籤時,我爲每個標籤設置了標籤。我有一個NSMutableArray名爲wordArray。現在,我想檢查我的字符串是wordArray或不可用, 我可以檢查這個使用:如何在iPhone中獲取UILabel標籤

[wordArray containsObject:wordStr]; 

用於動態創建標籤:

UILabel *wordLabl; 
int tagValue3 = 1; 
for (int iloop = 0; iloop < [wordArray count]; iloop++) 
{ 

    wordLabl = [self addwordLabelRect:CGRectMake(80 * iloop + 20, 420 , 100,  20)andTag:tagValue3];//30 + 35 30 * iloop+ 
    [self.view addSubview:wordLabl]; 
    tagValue3 += 1; 
} 

-(UILabel *)addwordLabelRect:(CGRect)rect andTag:(int)integerValue 
{ 
wordLabel = [[UILabel alloc] init]; 
wordLabel.frame = rect; 
wordLabel.userInteractionEnabled = YES; 
wordLabel.tag = integerValue; 
wordLabel.backgroundColor = [UIColor clearColor]; 
wordLabel.font = [UIFont systemFontOfSize:15]; 
wordLabel.text = [NSString stringWithFormat:@"%@",[wordArray objectAtIndex:integerValue - 1]]; 
wordLabel.textAlignment = NSTextAlignmentCenter; 
wordLabel.textColor = [UIColor whiteColor]; 

return wordLabel; 
} 

使用上面的代碼中,我創建標籤和標籤。 但是,如果wordArray包含字符串我想要更改該標籤的textColor.I認爲這可以使用標籤來完成,但我怎樣才能獲得標籤的標籤值。

+0

你可以做的是存儲這些標籤在數組中標記,然後根據該標籤獲取標籤。你可以輕鬆地做到我的朋友.... – NiravPatel

+0

你是否在'NSMutableArray'中存儲了創建的'UILabels'?顯示您的代碼 –

+0

如果您提供代碼,將有助於提供精確的解決方案 –

回答

0

我想你正在做類似的設置標籤?

for (NSUInteger i = 0; i < [wordArray count]; ++i) { 
    UILabel * label; 
    // setup your label... 
    [label setTag:i]; 
    [yourView addSubview:label]; 
} 

如果是這樣,只是做:

NSUInteger index = [wordArray indexOfObject:wordStr]; 
if (index != NSNotFound) { 
    UILabel * label = [yourView viewWithTag:index]; 
    // do whatever you want with your label 
} 

好運。

+0

如果'yourView'具有多個具有相同標記的對象,該怎麼辦?哪一個返回?如果返回的視圖不是'UILabel',那麼你的代碼如何處理? – Popeye

0

如果你想從它的標籤獲得UILabel。 你可以用下面的循環

int i=0; 
for (NSObject *view in self.View.subviews) 
{ 
    if ([view isKindOfClass:[UILabel class]]) 
    { 
     label = (UILabel *)[[self view] viewWithTag:wordArray[i]]; 
     NSLog(@"%@",label.text); 
     //here you get your label 
    } 
    i++; 
} 
1

對不起,我忽略了你的代碼...你只需要添加要訪問相應的標籤下面幾行:

if([wordArray containsObject:wordStr]) 
{ 
UILabel *label = (UILabel *) [self.view viewWithTag:([wordArray indexOfObject:wordStr] - 1)];//since u started tag assignment from 1 
label.textcolor = [UIColor yellowColor]; 
}