NSString *readMessage = @"在...注冊並創建賬戶的同時,我接受服務條款和隱私條款";
UITextView *textView = [[UITextView alloc] init];
textView.textColor = [UIColor blackColor];
textView.font = [UIFont systemFontOfSize:14];
NSAttributedString *attri = [NSMutableAttributedString attributedStringWithMessage:readMessage paragraphSpacing:0 lineSpacing:0 firstStr:@"服務條款" secendStr:@"隱私條款"];
textView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor blueColor]}; // 修改可點擊文字的顏色
textView.attributedText = attri;
textView.delegate = self;
[self.reginView addSubview:textView];
textView.backgroundColor = [UIColor clearColor];
textView.editable = NO;
[self.view addSubView: textView];
//代理:
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
NSRange range = [self.readMessage rangeOfString:@"服務條款"];//
if (characterRange.location == range.location) {//位置是否相同
//跳轉的控制器或頁面
// UserFileVC *userFileVC = [[UserFileVC alloc] init];
// [self presentViewController:userFileVC animated:YES completion:nil];
return NO; //這里必須返回,否則會出現長按崩潰的bug
}else {
NSRange otherRange = [self.readMessage rangeOfString:@"隱私條款"];
if (characterRange.location == otherRange.location) {
//跳轉的控制器或頁面
// UserFileVC *userFileVC = [[UserFileVC alloc] init];
// [self presentViewController:userFileVC animated:YES completion:nil];
}
return NO; //這里必須返回,否則會出現長按崩潰的bug
}
return YES;
}
//分類方法如下:(一般寫在分類方法中)
+ (NSAttributedString *)attributedStringWithMessage:(NSString *)message paragraphSpacing:(CGFloat)spacing lineSpacing:(CGFloat)lineSpace firstStr:(NSString *)firstStr secendStr:(NSString *)secendStr{
// 設置屬性
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
// 設置行間距
paragraphStyle.paragraphSpacing = spacing; // 段落間距
paragraphStyle.lineSpacing = lineSpace; // 行間距
NSDictionary *attributes = @{
NSForegroundColorAttributeName:[UIColor blackColor],
NSParagraphStyleAttributeName:paragraphStyle
};
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:message attributes:attributes];
[attrStr addAttributes:@{
NSLinkAttributeName:firstStr
}
range:[message rangeOfString:firstStr]];
[attrStr addAttributes:@{
NSLinkAttributeName:secendStr
}
range:[message rangeOfString:secendStr]];
return attrStr;
}
上面的代碼還有個bug還未解決,就是只要長按那個textView控件就去觸發這個方法(超鏈接),待之后想到后再更新。
2017.12.3 晚
