文本控件之UILabel

特性:可點擊的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;
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容