實現(xiàn)效果
UITextView *protocolTV = [[UITextView alloc] initWithFrame:CGRectZero];
protocolTV.editable=NO;
protocolTV.delegate=self;
NSMutableParagraphStyle *paragraph = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
//設(shè)置text文字居中
paragraph.alignment=NSTextAlignmentCenter;
protocolTV.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
//設(shè)置添加鏈接部分文字的顏色
protocolTV.linkTextAttributes = @{NSForegroundColorAttributeName:TextBodyColor};
[wechatView addSubview:protocolTV];
NSString *str = @"注冊登錄即代表同意XX的服務(wù)協(xié)議和隱私條款";
NSRangeprotocalRange = [strrangeOfString:@"服務(wù)協(xié)議"];
NSRangeprivacyRange = [strrangeOfString:@"隱私條款"];
NSMutableAttributedString *privacyMutableAttrStr = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFang SC" size: 12],NSForegroundColorAttributeName:TextBodyColor,NSParagraphStyleAttributeName:paragraph}];
//給需要 點擊的部分添加鏈接
[privacyMutableAttrStr addAttributes:@{NSLinkAttributeName:@"privacy://",NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Semibold" size: 12],NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)} range:privacyRange];
[privacyMutableAttrStr addAttributes:@{NSLinkAttributeName:@"protocal://",NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Semibold" size: 12],NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)} range:protocalRange];
protocolTV.attributedText= privacyMutableAttrStr;
[protocolTV mas_makeConstraints:^(MASConstraintMaker*make) {
? ? ? ? ? ?make.top.equalTo(self.wechatBtn.mas_bottom).offset(24);
? ? ? ? ? ?make.centerX.equalTo(bgview.mas_centerX);
? ? ? ? ? ?make.left.right.equalTo(bgview);
? ? ? ? ? ?make.height.mas_equalTo(15);
? ? ? ? ? ?make.width.equalTo(bgview.mas_width);
?}];
#pragma mark - UITextViewDelegate
-(BOOL)textView:(UITextView*)textViewshouldInteractWithURL:(NSURL*)URLinRange:(NSRange)characterRangeinteraction:(UITextItemInteraction)interaction{
? ? if ([URL.scheme isEqualToString:@"privacy"]) {
//這里調(diào)用方法跳到隱私條款頁面
? ? ? ? returnNO;
? ? }
? ? if ([URL.scheme isEqualToString:@"protocal"]) {
//這里調(diào)用方法跳到服務(wù)協(xié)議頁面
? ? ? ? returnNO;
? ? }
? ??return YES;
}
其中也有遇到問題:UITextView文本內(nèi)容居中
需要為文本設(shè)置NSMutableParagraphStyle
NSMutableParagraphStyle *paragraph = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
//設(shè)置text文字居中
paragraph.alignment=NSTextAlignmentCenter;
再設(shè)置NSMutableAttributedString
NSParagraphStyleAttributeName:paragraph ? ?設(shè)置段落樣式
此解決方案來自iOS — NSMutableAttributedString和NSMutableParagraphStyle