字符点击效果实现——YYLabel和YYTextHighlight

在字符串中,指定某字符子串的交互效果,使用YYLabelYYTextHighlight进行设置NSAttributedString来实现。

效果图


Simulator Screen Shot - iPhone 11 Pro Max - 2020-01-02 at 13.45.32.png

代码示例
实例化YYLabel

YYLabel *label = [[YYLabel alloc] initWithFrame:CGRectMake(10, 10, (self.view.frame.size.width - 20), 100)];
[self.view addSubview:label];
label.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
label.numberOfLines = 0;

实例化字符NSAttributedString

NSString *string = @"我已阅读并同意服务平台相关协议和条款《用户服务协议》《法律声明》";
NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc] initWithString:string];

[attributed setAttribute:NSForegroundColorAttributeName value:UIColor.blueColor range:[string rangeOfString:@"《用户服务协议》"]];
[attributed setAttribute:NSForegroundColorAttributeName value:UIColor.systemPinkColor range:[string rangeOfString:@"《法律声明》"]];

实例化YYTextHighlight

YYTextHighlight *protocolHightlight = [[YYTextHighlight alloc] init];
protocolHightlight.userInfo = @{@"协议":@"《用户服务协议》"};
[protocolHightlight setColor:UIColor.orangeColor];
[attributed setTextHighlight:protocolHightlight range:[string rangeOfString:@"《用户服务协议》"]];
    
YYTextHighlight *layHightlight = [[YYTextHighlight alloc] init];
layHightlight.userInfo = @{@"声明":@"《法律声明》"};
[layHightlight setColor:UIColor.yellowColor];
YYTextShadow *layShadow = [YYTextShadow new];
layShadow.color = UIColor.greenColor;
layShadow.radius = 5;
[layHightlight setShadow:layShadow];
[attributed setTextHighlight:layHightlight range:[string rangeOfString:@"《法律声明》"]];
attributed.lineSpacing = 3;
attributed.paragraphSpacing = 5;
label.attributedText = attributed;

点击效果

label.highlightTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        NSLog(@"%@, %@, %@, %@", containerView, text.string, NSStringFromRange(range), NSStringFromCGRect(rect));
        NSString *string = [text.string substringWithRange:range];
        NSLog(@"\n %@", string);
    };

交互结果

2020-01-02 13:52:16.276939+0800 DemoLabelClick[2705:120197] >, 我已阅读并同意服务平台相关协议和条款《用户服务协议》《法律声明》, {18, 8}, {{216, 41.280000000000001}, {96, 16.799999999999997}}
2020-01-02 13:52:16.277114+0800 DemoLabelClick[2705:120197] 
 《用户服务协议》

2020-01-02 13:52:25.209562+0800 DemoLabelClick[2705:120197] >, 我已阅读并同意服务平台相关协议和条款《用户服务协议》《法律声明》, {26, 6}, {{312, 41.280000000000001}, {72, 16.799999999999997}}
2020-01-02 13:52:25.209751+0800 DemoLabelClick[2705:120197] 
 《法律声明》

你可能感兴趣的:(字符点击效果实现——YYLabel和YYTextHighlight)