【iOS】自定义UITextView富文本超链接的颜色

默认情况下,可以直接通过设置NSAttributedString的颜色属性来修改NSAttributedString不同区域的颜色,但是在 UITextView 中,默认情况下超链接的颜色是系统设置的,无法直接通过NSAttributedString 来修改,默认就是蓝色的,如果想要修改默认的颜色,可以通过自定义UITextView,修改linkTextAttributes的属性来完成,或者直接设置UITextView的linkTextAttributes属性

自定义UITextView

  1. 自定义UITextView,设置链接的颜色为红色
@interface LCCustomTextView : UITextView

@end

@implementation LCCustomTextView

- (NSDictionary<NSAttributedStringKey, id> *)linkTextAttributes {
    return @{NSForegroundColorAttributeName : [UIColor redColor]};
}

@end
  1. 使用自定义UITextView
    self.textView = [[LCCustomTextView alloc] initWithFrame:CGRectMake(100, 100, 300, 100)];
    self.textView.delegate = self;
    [self.view addSubview:self.textView];
    
    NSString *text = @"测试富文本链接的颜色,百度一下";
    NSRange textRange = [text rangeOfString:text];
    NSRange linkRange = [text rangeOfString:@"百度一下"];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:textRange];
    [attributedString addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"www.baidu.com"] range:linkRange];
    //[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:linkRange];
    self.textView.attributedText = attributedString;
  1. 显示效果如下
    在这里插入图片描述

直接设置UITextView的linkTextAttributes属性

    NSString *text = @"测试富文本链接的颜色,百度一下";
    NSRange textRange = [text rangeOfString:text];
    NSRange linkRange = [text rangeOfString:@"百度一下"];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:textRange];
    [attributedString addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"www.baidu.com"] range:linkRange];
    
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 200, 300, 100)];
    self.textView.delegate = self;
    self.textView.linkTextAttributes = @{NSForegroundColorAttributeName : [UIColor grayColor]};
    self.textView.attributedText = attributedString;
    [self.view addSubview:self.textView];

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值