检测哈希标签#,提及标签@,在 iOS 中就像在 Twitter 应用程序中一样 [英] Detect hash tags #, mention tags @, in iOS like in Twitter App

查看:30
本文介绍了检测哈希标签#,提及标签@,在 iOS 中就像在 Twitter 应用程序中一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检测描述 UILabel 中给出的 #Tags 并将文本颜色更改为 [UIColor BlueColor]; 在我无法做到的地方将 UILabel 中的特定文本颜色更改为蓝色.现在我在自定义 UITableViewCell 中使用这个 UILabel.有没有办法解决这个问题,通过文本颜色区分 #Tags 和普通文本?有人可以帮我解决这个问题吗?

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 ?

推荐答案

-(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;
}

这篇关于检测哈希标签#,提及标签@,在 iOS 中就像在 Twitter 应用程序中一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆