Label中的文字添加点击事件
-
GitHub地址:https://github.com/lyb5834/YBAttributeTextTapAction
-
以前老师讲过类似的功能,自己懒得回头看了,找了很多第三方的,感觉这个小巧便利,作者只是扩展了分类,实现起来代码也少.先来个效果图
- 自己的项目,直接上代码
- (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<likeArr.count; 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:@"点击了“%@”字符
range: %@
index: %ld
跳转到"%@"的个人界面",string,NSStringFromRange(range),index,string];
ChaosAlertShow(message, @"取消");
CLog(@"%@",message);
}