iOS开发小技巧 - label中的文字添加点击事件

Label中的文字添加点击事件

iOS开发小技巧 - 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<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:@"点击了“%@”字符\nrange: %@\nindex: %ld \n跳转到\"%@\"的个人界面",string,NSStringFromRange(range),index,string]; ChaosAlertShow(message, @"取消"); CLog(@"%@",message); }
上一篇:关于原生的Javascript


下一篇:C#设计模式之原型模式