特性:可点击的UILabel
很多视觉稿中都存在这样的富文本控件:一个关键词具有可点击,点击后会打开一个新页面。
可以参考github仓库:MZSelectableLabel,鉴于网络上使用demo太少,这里附上一例
MZSelectableLabel *licenseLabel = [[MZSelectableLabel alloc] init];
licenseLabel.frame = CGRectMake(kLeftRightPadding, greenButton.bottom + 10, SCREEN_WIDTH - 2 * kLeftRightPadding, 18);
licenseLabel.textAlignment = NSTextAlignmentCenter;
licenseLabel.backgroundColor = [UIColor clearColor];
licenseLabel.userInteractionEnabled = YES;
licenseLabel.attributedText = [NSAttributedString attributeStringWithBasePrefix:@"点击同意代表你同意" keyWordSuffix:@"《XX服务协议》"];
[licenseLabel setSelectableRange:[licenseLabel.text rangeOfString:@"《XX服务协议》"]];
[self.view addSubview:licenseLabel];
@implementation NSAttributedString (Color)
+ (NSAttributedString *)attributeStringWithBasePrefix:(NSString *)basePrefix keyWordSuffix:(NSString *)keyWordSuffix
{
NSMutableAttributedString *mergerString = [[NSMutableAttributedString alloc] init];
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.alignment = NSTextAlignmentCenter;
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:basePrefix];
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:13.0],
NSForegroundColorAttributeName:HEXCOLOR_ALPHA(@"#1D1D26", 0.5),
NSParagraphStyleAttributeName:paragraphStyle};
[attributedString setAttributes:attributes range:NSMakeRange(0, [attributedString length])];
[mergerString appendAttributedString:attributedString];
}
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:keyWordSuffix];
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:13.0],
NSForegroundColorAttributeName:HEXCOLOR(@"#42C642"),
NSParagraphStyleAttributeName:paragraphStyle};
[attributedString setAttributes:attributes range:NSMakeRange(0, [attributedString length])];
[mergerString appendAttributedString:attributedString];
}
return mergerString;
}