文本控件之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;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容