我們在開發(fā)過程中會遇到這樣的需求陆馁。用戶注冊合愈,或者做些其他操作的時(shí)候我們需要在下方加上這樣一段話:注冊代表你遵守我們的《用戶協(xié)議》击狮,《隱私條款》這兩個(gè)是鏈接益老,那么接下來我們改怎么做呢彪蓬,先上圖再說話
文本鏈接.gif
如果我們按照平常的想法在label上面顯示文字捺萌,然后給label加上手勢也可以實(shí)現(xiàn),那么鏈接多的話桃纯,你就要判斷點(diǎn)擊手勢的區(qū)域,感覺麻煩态坦,那么蘋果給我們提供了很好的方法富文本NSMutableAttributedString。
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 100, 375, 100)];
textView.backgroundColor = [UIColor cyanColor];
//創(chuàng)建初始化文本的顏色驮配,以及字體大小
NSDictionary *dictionary = @{NSFontAttributeName:[UIFont systemFontOfSize:17],NSForegroundColorAttributeName:[UIColor yellowColor]};
NSString * string = @" 跳轉(zhuǎn)到百度\n\n 跳轉(zhuǎn)到簡書";
//創(chuàng)建富文本
NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:string attributes:dictionary];
//實(shí)現(xiàn)文本鏈接
[attributeStr addAttribute:NSLinkAttributeName value:@"http://www.reibang.com" range:[string rangeOfString:@"簡書"]];
[attributeStr addAttribute:NSLinkAttributeName value:@"http://www.baidu.com" range:[string rangeOfString:@"百度"]];
// textView.tintColor = [UIColor redColor];//調(diào)節(jié)文本鏈接字體的顏色
textView.attributedText = attributeStr;
textView.editable = NO;
上面的方法基本事件點(diǎn)擊點(diǎn)解跳轉(zhuǎn)的功能,當(dāng)然你也可以遵守textview的delegate在
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
return YES;
}
代理方法里面做你想要的操作琐旁,可是呢,有時(shí)后文字是分條顯示的 第一條灰殴,第二條,但是又不讓用文字牺陶,而是用上面的小點(diǎn)圖片顯示的,這就需要插入圖片了
//文本插入圖片
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"red_2"];
//圖片大小不合適 可以調(diào)整
attachment.bounds = CGRectMake(0, 0, 8, 8);
NSMutableAttributedString *attachmentString = (NSMutableAttributedString *)[NSAttributedString attributedStringWithAttachment:attachment];
//你想要插入圖片的位置
[textView.textStorage insertAttributedString:attachmentString atIndex:0];
[textView.textStorage insertAttributedString:attachmentString atIndex:10];
富文本里面還有好多東西掰伸,有興趣的小伙伴可以研究一下