博客> UILabel 中任意文字 添加监听事件
UILabel 中任意文字 添加监听事件
2017-11-23 12:54 评论:0 阅读:830 wangwei1
ios UIlabel 中任意文字 添加监听事件

平时我们在UIAlertViewController中会出现联系电话等 或者其他label里面均会出现需求 Label中文字有响应事件。 感谢LYB这位作者的UILabel+YBAttributeTextTapAction.h的扩展。

//需要点击的字符相同

NSString *label_text1 = @"我是个抽奖Label, 点我有奖,点我没奖哦";

NSMutableAttributedString *attributedString1 = [[NSMutableAttributedString alloc]initWithString:label_text1];

[attributedString1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, label_text1.length)];

[attributedString1 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(12, 2)];

[attributedString1 addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(17, 2)];

UILabel *ybLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, self.view.bounds.size.width - 20, 60)];
ybLabel1.backgroundColor = [UIColor yellowColor];
ybLabel1.numberOfLines = 2;
ybLabel1.attributedText = attributedString1;
[self.view addSubview:ybLabel1];
// 协议
[ybLabel1 yb_addAttributeTapActionWithStrings:@[@"点我",@"点我"] delegate:self];

   //需要点击的字符不同
NSString *label_text2 = @"您好!您是小明吗?你中奖了,领取地址“www.yb.com”,领奖码“9527”";
NSMutableAttributedString *attributedString2 = [[NSMutableAttributedString alloc]initWithString:label_text2];
[attributedString2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, label_text2.length)];
[attributedString2 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(19, 10)];
[attributedString2 addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(35, 4)];

UILabel *ybLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(10, 200, self.view.bounds.size.width - 20, 60)];
ybLabel2.backgroundColor = [UIColor lightGrayColor];
ybLabel2.numberOfLines = 2;
ybLabel2.attributedText = attributedString2;
[self.view addSubview:ybLabel2];
// block 回调
[ybLabel2 yb_addAttributeTapActionWithStrings:@[@"www.yb.com",@"9527"] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
    NSString *message = [NSString stringWithFormat:@"点击了“%@”字符\nrange: %@\nindex: %ld",string,NSStringFromRange(range),index];
    YBAlertShow(message, @"取消");
}];

//delegate

- (void)yb_attributeTapReturnString:(NSString *)string range:(NSRange)range index:(NSInteger)index

{

 NSString *message = [NSString stringWithFormat:@"点击了“%@”字符\nrange: %@\nindex: %ld",string,NSStringFromRange(range),index];

YBAlertShow(message, @"取消");
}

链接 (http://www.code4app.com/forum.php?mod=viewthread&tid=9242&extra=page=1&filter=sortid&sortid=1)

收藏
0
sina weixin mail 回到顶部