在日常開發(fā)中顽分,我們會(huì)遇到這樣的需求货矮,就是一段文字說明中的某一段字是要有點(diǎn)擊事件的碌上,并且顏色也要跟整段文字區(qū)分開來,這時(shí)候用textView就比較方便了丘逸,效果如下:
首先給一個(gè)textView的內(nèi)容:
static NSString *content = @"? 原手機(jī)號(hào)碼無法收到驗(yàn)證碼单鹿? 點(diǎn)擊 其他方式修改\n? 如需幫助掀宋,請(qǐng)聯(lián)系客服 010-123456 查詢深纲。";
然后設(shè)置下textView的屬性
// 設(shè)置屬性
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
// 設(shè)置行間距
paragraphStyle.paragraphSpacing = 2; // 段落間距
paragraphStyle.lineSpacing = 1; // 行間距
NSDictionary *attributes = @{
NSForegroundColorAttributeName:[UIColor blackColor],
NSParagraphStyleAttributeName:paragraphStyle
};
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:message attributes:attributes];
[attrStr addAttributes:@{
NSLinkAttributeName:@"其他方式修改"
}
range:[message rangeOfString:@"其他方式修改"]];
[attrStr addAttributes:@{
NSLinkAttributeName:@"telprompt://010-123456"
}
range:[message rangeOfString:@"010-123456"]];
_textView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor blueColor]}; // 修改可點(diǎn)擊文字的顏色
_textView.attributedText = attrStr;
_textView.editable = NO;
_textView.scrollEnabled = NO;
_textView.delegate = self;
電話是可以直接撥打的,但是如果是一段文字劲妙,我們就需要去代理方法里實(shí)現(xiàn)我們要做的事:
// 其他方式修改
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
NSRange range = [content rangeOfString:@"其他方式修改"];
if (characterRange.location == range.location) {
// 做你想做的事
}
return YES;
}