1.簡單設(shè)置帶屬性的字符串
//定義一個NSMutableAttributedString帶屬性的字符串
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"hello[1_1] world![哈哈][微笑]"];
//設(shè)置屬性
[str setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:60], NSForegroundColorAttributeName:[UIColor redColor], NSBackgroundColorAttributeName:[UIColor greenColor], NSUnderlineColorAttributeName:[UIColorblueColor], NSUnderlineStyleAttributeName:@(NSUnderlineStyleDouble)} range:NSMakeRange(0, 5)];
//顯示
_label.attributedText = str;
-
用表情代替帶【】的文字(qq會話辆亏,微信會話)
//定義正則表達式
NSString *pattern = @"\\[[\u4E00-\u9FA5]+\\]";
NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:patternoptions:NSRegularExpressionCaseInsensitive error:nil];
NSString *text = @"hello[1_1] world![哈哈]";
得到符合表達式的數(shù)組NSTextCheckingResult類型的
NSArray *resultArray = [regular matchesInString:text options:0 range:NSMakeRange(0, text.length)];
//定義一個帶附件的字符串
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
for (NSTextCheckingResult *result in resultArray) {
//位置
NSRange range = result.range;
//得到附件
NSTextAttachment *attach = [[NSTextAttachment alloc] init];
//設(shè)置附件的圖片
attach.image = [UIImage imageNamed:@"d_guzhang"];
//得到附件生成的字符串
NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:attach];
//把文字替換成表情
[attStr replaceCharactersInRange:range withAttributedString:imageStr];
}
_label.attributedText = attStr;