特性:可點擊的UILabel
很多視覺稿中都存在這樣的富文本控件:一個關鍵詞具有可點擊,點擊后會打開一個新頁面。
InteractiveLabel.jpg
可以參考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;
}