iOS - 富文本添加超链接

1. 定义一个控制器TextView

(一般富文本使用Label,但是添加超链需要点击,故使用textview较为方便)
UITextView * contentTextView;
contentTextView = [[UITextView alloc] initWithFrame:CGRectMake(20, 50, 335,50)];
contentTextView.textColor = [UIColor blackColor];
[self.view addSubview: contentTextView];

2.给富文本添加超链接

//1.根据手机设置字体大小
 UIFont * textFont;
 if ([SDiPhoneVersion deviceSize] == iPhone35inch || [SDiPhoneVersion deviceSize] == iPhone4inch) {
        textFont = k_Helvetica_15;
 } else {
        textFont = k_Helvetica_16;
 }
//2. 定义一个字典,存储字体和色号
NSDictionary * dictionary = @{NSFontAttributeName:textFont,NSForegroundColorAttributeName:k_fontColor};
//定义一个字符串存储文本内容
NSString * string = NSLocalizedString(@"I accept www Controls Terms & Conditions", nil);
//3.初始化一个富文本,并将string内容赋值给它
NSMutableAttributedString *conditionsAttributeStr = [[NSMutableAttributedString alloc] initWithString:string attributes:dictionary];
//value:超链,range:要添加超链的文本位置
[conditionsAttributeStr addAttribute:NSLinkAttributeName value:@"https://......" range:[string rangeOfString:NSLocalizedString(@"Terms & Conditions", nil)]];

//4.给文本www设置字体和大小
NSString * str = NSLocalizedString(@"www", nil);
//获取要设置字体的文本的位置
NSRange fontRange = NSMakeRange([[conditionsAttributeStr string] rangeOfString:str].location,[[conditionsAttributeStr string] rangeOfString:str].length);
//value:设置字体和大小,range:要设置字体的文本的位置
[conditionsAttributeStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:DINOFFCPRO_FONT_FAMILY size:25] range:fontRange];

contentTextView.attributedText = conditionsAttributeStr;
contentTextView.editable = NO;
contentTextView.scrollEnabled = NO;

3. 效果图

富文本.png

你可能感兴趣的:(iOS - 富文本添加超链接)