实现效果
UITextView *protocolTV = [[UITextView alloc] initWithFrame:CGRectZero];
protocolTV.editable=NO;
protocolTV.delegate=self;
NSMutableParagraphStyle *paragraph = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
//设置text文字居中
paragraph.alignment=NSTextAlignmentCenter;
protocolTV.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
//设置添加链接部分文字的颜色
protocolTV.linkTextAttributes = @{NSForegroundColorAttributeName:TextBodyColor};
[wechatView addSubview:protocolTV];
NSString *str = @"注册登录即代表同意XX的服务协议和隐私条款";
NSRangeprotocalRange = [strrangeOfString:@"服务协议"];
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"]) {
//这里调用方法跳到隐私条款页面
returnNO;
}
if ([URL.scheme isEqualToString:@"protocal"]) {
//这里调用方法跳到服务协议页面
returnNO;
}
return YES;
}
其中也有遇到问题:UITextView文本内容居中
需要为文本设置NSMutableParagraphStyle
NSMutableParagraphStyle *paragraph = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
//设置text文字居中
paragraph.alignment=NSTextAlignmentCenter;
再设置NSMutableAttributedString
NSParagraphStyleAttributeName:paragraph 设置段落样式
此解决方案来自iOS — NSMutableAttributedString和NSMutableParagraphStyle