由于業(yè)務(wù)需要搞個(gè)文字跳轉(zhuǎn)網(wǎng)頁,網(wǎng)上的版本很多都很復(fù)雜,記錄個(gè)簡(jiǎn)單版本的.
1.首先創(chuàng)建個(gè)UITextView的子類.
如果需要滑動(dòng)View可以把-(void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer注釋取消.
@implementation UITextLinkView: UITextView
- (BOOL)canBecomeFirstResponder
{
return NO;
}
- (UITextRange *)selectedTextRange{
return nil;
}
-(void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer{
取消所有手勢(shì),如果需要其他的可以打開注釋.
// if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]] ) {
// gestureRecognizer.enabled = NO;
//}
// [super addGestureRecognizer:gestureRecognizer];
}
@end
2.創(chuàng)建textView
_detailTextView = [UITextLinkView new];
_detailTextView.textAlignment = NSTextAlignmentLeft;
// 修改可點(diǎn)擊文字的顏色
_detailTextView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor redColor],NSUnderlineStyleAttributeName:@(1)};
_detailTextView.editable = NO;
_detailTextView.scrollEnabled = NO;
//讓textVIew文字內(nèi)容邊距為0,便于設(shè)置約束.
_detailTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
3.添加文字
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 2; // 行間距
NSString * contentStr = @"啦啦啦";
NSString * jumpStr = @"點(diǎn)我跳轉(zhuǎn)";
NSString * urlStr = @"http://www.baidu.com";
contentStr = [ contentStr stringByAppendingString:jumpStr];
//這步是防止點(diǎn)擊鏈接后如果沒有文字,那么點(diǎn)擊textVIew后面的空白區(qū)域也會(huì)跳轉(zhuǎn)
contentStr = [ contentStr stringByAppendingString:@" "];
NSDictionary *attributes = @{
NSForegroundColorAttributeName:[UIColor blackColor],
NSParagraphStyleAttributeName:paragraphStyle};
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:contentStr attributes:attributes];
//添加跳轉(zhuǎn)文字及跳轉(zhuǎn)鏈接
[attrStr addAttribute:NSLinkAttributeName value:urlStr range:[contentStr rangeOfString:jumpStr]];
_detailTextView.attributedText = attrStr;