iOS7 textView处理URL链接 以及点击 长按手势的处理
2015-10-10 16:59
537 查看
举例1 :文本超链接
@property (weak,nonatomic) IBOutlet
UITextView *tv;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This
is an example by @marcelofabri_"];
[attributedString addAttribute:NSLinkAttributeName
value:@"username://marcelofabri_"
range:[[attributedString string] rangeOfString:@"@marcelofabri_"]];
NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor greenColor],
NSUnderlineColorAttributeName: [UIColor lightGrayColor],
NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
self.tv.linkTextAttributes = linkAttributes;
self.tv.attributedText = attributedString;
self.tv.delegate =self ;
self.tv.editable = NO;
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL
inRange:(NSRange)characterRange{
NSLog(@"%@",URL.absoluteString);
return NO ;
}
举例2 :文本:系统默认是双击 ,这里用单击实现
self.tv.dataDetectorTypes = UIDataDetectorTypeAll;self.tv.attributedText =
[[NSAttributedString alloc]initWithString:
@" +8602980000000.\r\n"
"My personal web site www.xxxxxx.com.\r\n"
"My E-mail address is XXXXX@gmail.com.\r\n"
"I was born in 1900-01-01."];
self.tv.editable = NO;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onlyTap:)];
[self.tv addGestureRecognizer:tap];
- (void)onlyTap:(UITapGestureRecognizer *)recognizer
{
CGPoint location = [recognizer locationInView:self.tv];
NSLog(@"Tap Gesture Coordinates: %.2f %.2f", location.x,
location.y);
NSString *tappedSentence = [self lineAtPosition:CGPointMake(location.x,
location.y)];
NSLog(@"%@",tappedSentence);
}
- (NSString *)lineAtPosition:(CGPoint)position
{
//eliminate scroll offset
position.y += _tv.contentOffset.y;
//get location in text from textposition at point
UITextPosition *tapPosition = [_tv closestPositionToPoint:position];
//fetch the word at this position (or nil, if not available)
UITextRange *textRange = [_tv.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularitySentence inDirection:UITextLayoutDirectionRight];
return [_tv textInRange:textRange];
}
参考资料:
http://stackoverflow.com/questions/15034652/tap-gesture-to-part-of-a-uitextview http://www.raywenderlich.com/48001/easily-overlooked-new-features-ios-7#textViewLinks
相关文章推荐
- iOS的音讯通知有两种方式,Badge Notification和Alert Notification
- iOS多工程依赖
- IOS 9 Remove CODE_SIGN_RESOURCE_RULES_PATH=$(SDKROOT)/ResourceRules.plist
- iOS开发--OC篇--OC类与对象
- IOS多线程
- iOS常用第三方框架
- iOS ARC MRC情况下重写setter getter方法
- 又发现一个很好的ios博客--颐和园
- ios第二天
- ios第一天
- iOS几何类方法总结
- iOS动画实现方式 animation key path
- iOS大侠博客
- iOS 8 AutoLayout与Size Class自悟
- iOS 支付宝支付
- 斯坦福大学iOS7应用开发笔记一(未完)
- iOS学习之升级Xcode之后VVDocumenter-Xcode不能用解决办法
- 谈谈iOS的layoutSubviews机制
- ios开发之IBOutlet和IBAction的区别
- RDVTabBarController--可自由定制的iOS底部导航控件