Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

objective c - Detect hash tags #, mention tags @, in iOS like in Twitter App

I need to Detect #Tags given in description UILabel and change text color as [UIColor BlueColor]; where i am not able to change particular text colors in UILabel to Blue. Now i am Using this UILabel in custom UITableViewCell. is there any way to solve this issue to differentiate #Tags and normal text by Text Colors ? can anybody help me to solve this ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
-(NSMutableAttributedString*)decorateTags:(NSString *)stringWithTags{


    NSError *error = nil;

    //For "Vijay #Apple Dev"
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\w+)" options:0 error:&error];

    //For "Vijay @Apple Dev"
    //NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"@(\w+)" options:0 error:&error];

    NSArray *matches = [regex matchesInString:stringWithTags options:0 range:NSMakeRange(0, stringWithTags.length)];
    NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:stringWithTags];

    NSInteger stringLength=[stringWithTags length];

    for (NSTextCheckingResult *match in matches) {

        NSRange wordRange = [match rangeAtIndex:1];

        NSString* word = [stringWithTags substringWithRange:wordRange];

        //Set Font
        UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:15.0f];
        [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, stringLength)];


        //Set Background Color
        UIColor *backgroundColor=[UIColor orangeColor];
        [attString addAttribute:NSBackgroundColorAttributeName value:backgroundColor range:wordRange];

        //Set Foreground Color
        UIColor *foregroundColor=[UIColor blueColor];
        [attString addAttribute:NSForegroundColorAttributeName value:foregroundColor range:wordRange];

        NSLog(@"Found tag %@", word);

    }

    // Set up your text field or label to show up the result

    //    yourTextField.attributedText = attString;
    //
    //    yourLabel.attributedText = attString;

    return attString;
}

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...