標籤:types 超連結 test ipa cto sel tac 代理 handle
對於 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 文本自由複製 超連結監聽