最近有個項目需要做一個可以對textView內(nèi)容進行交互的功能,因此做了一個類似微博展示Emotion豹绪、@somebody、#話題#以及鏈接的Demo申眼。
一瞒津、工具
1、RegexKitLite:github.com/samdeane/RegexKitLite
正則表達括尸,使用起來是非常方便巷蚪,由于是MAC模式,在使用的時候濒翻,需要進行以下操作:
使用 -fno-objc-arc 讓RegexKitLite支持ARC
2屁柏、導入libicucore.tbd動態(tài)庫
2、MJExtension: https://github.com/CoderMJLee/MJExtension
字典和模型之間互相轉換的超輕量級框架有送。
二前联、Demo結構
通過創(chuàng)建自定義的statusTextView展示帶有屬性的特殊字段內(nèi)容:鏈接、Emotion娶眷、話題以及@somebody等等似嗤。
?自定義TextView(statusTextView)
model
* specialPart
* status
* TZTextPart
tool
-?TZEmotionTool
-?TZEmotion
三、代碼解讀
1届宠、首先創(chuàng)建要展示的內(nèi)容(截取一段微博正文):
`@"@StephenCurry? “I'm Back”烁落!https://bbs.hupu.com (使用#秒拍#錄制,免流量看熱門短視頻M阕ⅰ) #庫里經(jīng)典比# 去年季后賽次輪伤塌,傷愈復出的庫里首戰(zhàn)面對開拓者就拿下40分9籃板8助攻,加時賽瘋砍17分轧铁,率隊逆轉獲勝晉級西決每聪。#StreeBall#? [吃元宵][吃元宵][吃元宵]";`
2、實例化展示內(nèi)容
在TZStatus頭文件聲明屬性
/** 正文內(nèi)容 */
@property (copy, nonatomic) NSString *contentText;
/** 帶屬性的微博信息內(nèi)容 */
@property (strong, nonatomic) NSAttributedString *attributedText;
在TZTextPart頭文件聲明屬性
/** 文字段內(nèi)容 */
@property (strong, nonatomic) NSString *partText;
/** 文字段范圍 */
@property (assign, nonatomic) NSRange range;
/** 是否是特殊文字 */
@property (assign, nonatomic, getter=isSpecial) BOOL special;
/** 是否是表情文字 */
@property (assign, nonatomic, getter=isEmotion) BOOL emotion;
在TZSpecialPart頭文件聲明屬性
/** 特殊段內(nèi)容 */
@property (strong, nonatomic) NSString *specialText;
/** 特殊段范圍 */
@property (assign, nonatomic) NSRange specialRange;
/** 特殊文字的矩形框 數(shù)組 */
@property (strong, nonatomic) NSArray *rects;
通過正則表達將NSString中的 “表情”齿风、“@somebody”药薯、“#話題#”、“鏈接”救斑、“普通字段” 區(qū)分開童本,并拼接成NSAttributedString:
- (NSAttributedString *)attributedTextWithText:(NSString *)contentText{
//? ? 利用contentText生成attributedText
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
//? ? 1.RegexKitLite正則表達方法
//? ? 表情的規(guī)則
NSString *emotionPattern = @"\\[[0-9a-zA-Z\\u4e00-\\u9fa5]+\\]";
//? ? @的規(guī)則
NSString *atPattern = @"@[0-9a-zA-Z\\u4e00-\\u9fa5_-]+";
//? ? #話題#的規(guī)則
NSString *topicPattern = @"#[0-9a-zA-Z\\u4e00-\\u9fa5]+#";
//? ? url鏈接的規(guī)則
NSString *urlPattern = @"\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/)))";
NSString *pattern = [NSString stringWithFormat:@"%@|%@|%@|%@", emotionPattern, atPattern, topicPattern, urlPattern];
//? ? 各種文字段的內(nèi)容
NSMutableArray *parts = [NSMutableArray array];
//? ? 2.遍歷所有內(nèi)容 選出特殊字段內(nèi)容
[contentText enumerateStringsMatchedByRegex:pattern usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
//? ? ? ? 沒有匹配的字段
if ((*capturedRanges).length == 0) return;
//? ? ? ? 收集特殊字段
TZTextPart *part = [[TZTextPart alloc] init];
part.partText = *capturedStrings;
part.range = *capturedRanges;
part.special = YES;
part.emotion = [part.partText hasPrefix:@"["] && [part.partText hasSuffix:@"]"];
[parts addObject:part];
}];
//? ? 3.遍歷所有內(nèi)容 選出普通字段內(nèi)容
[contentText enumerateStringsSeparatedByRegex:pattern usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
//? ? ? ? 沒有匹配的字段
if ((*capturedRanges).length == 0) return;
//? ? ? ? 收集普通字段
TZTextPart *part = [[TZTextPart alloc] init];
part.partText = *capturedStrings;
part.range = *capturedRanges;
[parts addObject:part];
}];
//? ? 4.將獲得的所有字段按 range 排序
[parts sortUsingComparator:^NSComparisonResult(TZTextPart? *_Nonnull part1, TZTextPart *_Nonnull part2) {//升序排列
if (part1.range.location > part2.range.location) {
return NSOrderedDescending;
}
return NSOrderedAscending;
}];
UIFont *font = [UIFont systemFontOfSize:15.0];
//? ? ? 儲存特殊屬性數(shù)組
NSMutableArray *specials = [NSMutableArray array];
//? ? 5.分別處理各文字段 設置內(nèi)容的屬性
for (TZTextPart *part in parts) {
NSAttributedString *substr = nil;
if (part.isEmotion) {//表情
NSTextAttachment *attch = [[NSTextAttachment alloc] init];
NSString *name = [TZEmotionTool emotionWithChs:part.partText].png;
if (name) { // 能找到對應的圖片
attch.image = [UIImage imageNamed:name];
attch.bounds = CGRectMake(0, -3, font.lineHeight, font.lineHeight);
substr = [NSAttributedString attributedStringWithAttachment:attch];
} else { // 表情圖片不存在
substr = [[NSAttributedString alloc] initWithString:part.partText];
}
}else if (part.special){//特殊文字
substr = [[NSAttributedString alloc] initWithString:part.partText attributes:@{
NSForegroundColorAttributeName:[UIColor blueColor]
}];
//? ? ? ? ? ? 將特殊文字段的 內(nèi)容 和 位置 保存起來
TZSpecialPart *specialPart = [[TZSpecialPart alloc] init];
specialPart.specialText = part.partText;
NSUInteger loc = part.range.location;
NSUInteger len = part.range.length;
specialPart.specialRange = NSMakeRange(loc, len);
[specials addObject:specialPart];
}else{//非特殊文字
substr = [[NSAttributedString alloc] initWithString:part.partText];
}
[attributedText appendAttributedString:substr];
}
[attributedText addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attributedText.length)];
//? ? 把specials 添加到? 0,1 的位置上(第一個字符的屬性上)
[attributedText addAttribute:@"specials" value:specials range:NSMakeRange(0, 1)];
return attributedText;
}
3脸候、在收集到特殊字段數(shù)組后穷娱,在自定義的textView中顯示出來绑蔫,并創(chuàng)建相應字段的點擊事件。
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event方法可以判斷是否響應textView內(nèi)的touch時間泵额。
/**
告訴系統(tǒng):觸摸點point是否在這個UI控件身上
*/
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
[self setupSpecialRects];
// ?找出被觸摸的特殊字符串
TZSpecialPart *specialPart = [self touchingSpecialWithPoint:point];
if (specialPart) {//觸摸到特殊字符串時才響應touch事件
return YES;
}else{
return NO;
}
}
/**
*? 找出被觸摸的特殊字符串
*/
-(TZSpecialPart *)touchingSpecialWithPoint:(CGPoint)point
{
NSArray *specials = [self.attributedText attribute:@"specials" atIndex:0 effectiveRange:nil];
for (TZSpecialPart *specialPart in specials){
for (NSValue *rectValue in specialPart.rects) {
//? ? ? ? ? ? 如果手指位置在 特定文字 位置
if(CGRectContainsPoint(rectValue.CGRectValue,point)){
return specialPart;
}
}
}
return nil;
}
點擊時尋找特殊字符串配深,并顯示出來
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
//? ? 1.獲取觸摸位置
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
//? ? 2.初始化特殊文字段的矩形框
[self setupSpecialRects];
//? ? 3.根據(jù)觸摸點獲得被觸摸的特殊字符串
TZSpecialPart *specialPart = [self touchingSpecialWithPoint:point];
//? ? 4.在被觸摸的特殊字符串后面顯示一段高亮的背景
for (NSValue *rectValue in specialPart.rects) {
//? ? ? 添加遮蓋
UIView *cover = [[UIView alloc] init];
cover.backgroundColor = [UIColor greenColor];
cover.frame = rectValue.CGRectValue;
cover.tag = TZCoverTag;
[self insertSubview:cover atIndex:0];
}
}