iOS 文本自由复制 超链接监听
Posted 怡情_老二
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 文本自由复制 超链接监听相关的知识,希望对你有一定的参考价值。
对于 Label 需要支持复制、超链接监听最好的方案就是使用UITextView 代替Label
设置TextView支持超链接
self.contentTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0); self.contentTextView.delegate = self; self.contentTextView.editable = NO; self.contentTextView.showsVerticalScrollIndicator = NO; self.contentTextView.dataDetectorTypes = UIDataDetectorTypeLink;
TextView 默认超链接点击 是应用外跳转
要想实现应用内跳转,需要遵循 UITextViewDelegate 实现UITextViewDelegate代理方法,拦截到超链接URL 自己在应用内做跳转
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { if ([self.delegate respondsToSelector:@selector(clickUrl:)]) { [self.delegate clickUrl:[URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; } NSLog(@"%@", URL.absoluteString); return NO; }
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
return YES 除了监听点击事件之外还是监听长按事件 长按弹出copy share 按钮 ,不过点击open 会跳转到应用外打开链接,
return NO 只监听链接的点击事件 不监听其他事件 例如长按弹出copy share 按钮 , 这样我们可以自定义 弹出按钮 ,然后做copy 和 应用内打开链接等操作
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { if ([self.delegate respondsToSelector:@selector(clickUrl:)]) { [self.delegate clickUrl:[URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; } return NO; }
控制器里面 实现代理
- (void)clickUrl:(NSString *)url { UIAlertControllerStyle style = UIAlertControllerStyleActionSheet; if ([PhoneUtil isPadDevice]) { // 适配iPad style = UIAlertControllerStyleAlert; } UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:url message:nil preferredStyle:style]; // 处理复制 UIAlertAction *copyAction = [UIAlertAction actionWithTitle:getStringByKey(@"string_key_616") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; pasteboard.string = url; }]; // 处理链接点击应用内跳转 UIAlertAction *openAction = [UIAlertAction actionWithTitle:getStringByKey(@"string_key_1370") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { UIStoryboard *sb=[UIStoryboard storyboardWithName:@"Setting" bundle:[NSBundle mainBundle]]; WebViewVC *vc=[sb instantiateViewControllerWithIdentifier:@"WebViewVC"]; vc.url = url; [self.navigationController pushViewController:vc animated:YES]; }]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:getStringByKey(@"string_key_219") style:UIAlertActionStyleCancel handler:nil]; [alertVC addAction:copyAction]; [alertVC addAction:openAction]; [alertVC addAction:cancelAction]; [self.navigationController presentViewController:alertVC animated:YES completion:nil]; }
以上是关于iOS 文本自由复制 超链接监听的主要内容,如果未能解决你的问题,请参考以下文章