在字符串中,指定某字符子串的交互效果,使用YYLabel
和YYTextHighlight
进行设置NSAttributedString
来实现。
效果图
代码示例
实例化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] <YYLabel: 0x7f85eb7140b0; frame = (10 10; 394 100); text = '我已阅读并同意服务平台相关协议和条款《用户服务协议...'; opaque = NO; layer = <YYAsyncLayer: 0x600003dae190>>, 我已阅读并同意服务平台相关协议和条款《用户服务协议》《法律声明》, {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] <YYLabel: 0x7f85eb7140b0; frame = (10 10; 394 100); text = '我已阅读并同意服务平台相关协议和条款《用户服务协议...'; opaque = NO; layer = <YYAsyncLayer: 0x600003dae190>>, 我已阅读并同意服务平台相关协议和条款《用户服务协议》《法律声明》, {26, 6}, {{312, 41.280000000000001}, {72, 16.799999999999997}}
2020-01-02 13:52:25.209751+0800 DemoLabelClick[2705:120197]
《法律声明》