如何将Label设置为NSString

时间:2012-04-23 20:30:30

标签: ios nsstring uilabel

您好我有2个标签textview和labelsText,在这个方法中它们是string1和string2但是我真的无法让它生成textview string1和labelsText string2

这是代码:

-(void)findEqualsIn:(NSString *)string1 and:(NSString *)string2 {
    NSMutableArray *string1chars = [[NSMutableArray alloc] init];
    NSMutableArray *string2chars = [[NSMutableArray alloc] init];


    //filling the string1chars array
    for (int i = 0; i < [string1 length]; i++) {
        [string1chars addObject:[NSString stringWithFormat:@"%c", [string1 characterAtIndex:i]]];
    }

    //filling the string2chars array
    for (int i = 0; i < [string2 length]; i++) {
        [string2chars addObject:[NSString stringWithFormat:@"%c", [string2 characterAtIndex:i]]];
    }

    //checking if they have some letters in common on the same spot
    for (int i = 0; i < [string1chars count] && i < [string2chars count]; i++) {
        if ([[string1chars objectAtIndex:i] isEqualToString:[string2chars objectAtIndex:i]]) {
            //change the color of the character at index i to green
        } else {
            //change the color of the character at index i to the standard color

        }
    }

3 个答案:

答案 0 :(得分:0)

uilabeluitextview中的所有文字必须是相同的字体/颜色。

答案 1 :(得分:0)

由于iOS SDK中没有内置的richt文本组件,因此仍然可以使用很少的实现。我建议您使用FTCoreText创建UIL用户(不可编辑)和可编辑的EGOTextView

答案 2 :(得分:0)

您可以在其中添加每个字母的多个标签,并使其显示为仅在1个标签中。这需要这样的事情:

//make sure the first word is always the one the user gave so you don't show him/her the hidden string
- (void)outputColoredLabelsTo:(UIView *)theView with:(NSString *)word1 and:(NSString *)word2 {
    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 20, 0, 0)] autorelease];

    for (int i = 0; i < [word1 length] && i < [word2 length]; i++) {
        NSString *value = [NSString stringWithFormat:@"%c", [word1 characterAtIndex:i]];
        CGSize size = [value sizeWithFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]];
        label = [[UILabel alloc] initWithFrame:CGRectMake(label.frame.origin.x + label.frame.size.width, label.frame.origin.y, size.width, size.height)];
        [label setText:value];

        if ([word1 characterAtIndex:i] == [word2 characterAtIndex:i]) {
            NSLog(@"Match found at index %i (letter %c)", i, [word1 characterAtIndex:i]);
            [label setTextColor:[UIColor greenColor]];
        } else {
            NSLog(@"No match found at index %i (printing letter %c)", i, [word1 characterAtIndex:1]);
            [label setTextColor:[UIColor blackColor]];
        }

        [theView addSubview:label];
    }
}