Label中的文字添加點擊事件
以前老師講過類似的功能,自己懶得回頭看了,找了很多第三方的,感覺這個小巧便利,作者只是擴展了分類,實現起來代碼也少.先來個效果圖
自己的項目,直接上代碼
- (void)setTopicModel:(CYQTopicModel *)topicModel
{
_topicModel = topicModel;
NSArray *likeArr = self.topicModel.userLike;
if (!likeArr.count) return; // 沒有點贊的直接返回
NSMutableArray *ranges = [NSMutableArray array]; // 特殊字符的Range集合,修改文字顏色用
NSMutableArray *actionStrs = [NSMutableArray array]; // 將要添加點擊事件的字符串集合
NSString *string = @"";
for (int i=0; i
CYQAccount *account = likeArr[i];
// 拼接字符串
string = [string stringByAppendingString:account.userName];
[actionStrs addObject:account.userName];
if (i != likeArr.count - 1) {
string = [string stringByAppendingString:@","];
}
// 特殊字符的Range
NSRange range = [string rangeOfString:account.userName];
[ranges addObject:[NSValue valueWithRange:range]];
}
// 轉換成富文本字符串
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:string];
[attrStr addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14.f]} range:NSMakeRange(0, string.length)];
// 最好設置一下行高,不設的話默認是0
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineSpacing = 0;
[attrStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, string.length)];
// 給指定文字添加顏色
for (NSValue *rangeVal in ranges) {
[attrStr addAttributes:@{NSForegroundColorAttributeName : [UIColor blueColor]} range:rangeVal.rangeValue];
}
self.likeLabel.attributedText = attrStr;
// 給指定文字添加點擊事件,并設置代理,代理中監聽點擊
[self.likeLabel yb_addAttributeTapActionWithStrings:actionStrs delegate:self];
}
代理中具體的事件沒有處理,方法中的index參數跟模型集合一一對應,到時候直接拿到相應的模型來做事情就可以
// 彈窗的宏
#define ChaosAlertShow(messageText,buttonName) \
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:(messageText) \
delegate:nil cancelButtonTitle:(buttonName) otherButtonTitles: nil];\
[alert show];
#pragma mark - YBAttributeTapActionDelegate
- (void)yb_attributeTapReturnString:(NSString *)string range:(NSRange)range index:(NSInteger)index
{
NSString *message = [NSString stringWithFormat:@"點擊了“%@”字符\nrange: %@\nindex: %ld \n跳轉到\"%@\"的個人界面",string,NSStringFromRange(range),index,string];
ChaosAlertShow(message, @"取消");
CLog(@"%@",message);
}