iOS開發小技巧 - label中的文字添加點擊事件


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);

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM