5

在我的 iPhone 应用程序中,一个 UITextView 包含一个 URL。我想在 UIWebView 中打开这个 URL 而不是在 Safari 中打开它?我的 UITextView 包含一些数据以及一个 URL。在某些情况下,没有。的 URL 可以不止一个。

谢谢桑迪

4

3 回答 3

11

您可以按照以下步骤操作:

  1. 勾选以下UITextView取自 Xib 或 Storyboard 的属性。

检查 UITextView 的这些属性

或为动态获取的 textview 编写这些。

textview.delegate=self;
textview.selectable=YES;
textView.dataDetectorTypes = UIDataDetectorTypeLink;
  1. 现在编写以下delegate方法:
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
 NSLog(@"URL: %@", URL);
//You can do anything with the URL here (like open in other web view).
    return NO;
}

我想你正在寻找那个。

于 2014-01-24T15:43:01.483 回答
9

UITextView 能够检测 URL 并相应地嵌入超链接。您可以在以下位置打开该选项:

myTextView.dataDetectorTypes = UIDataDetectorTypeLink;

然后您需要配置您的应用程序以捕获此 URL 请求并让您的应用程序处理它。我在 github 上发布了一个样板类,这可能是最简单的方法:http: //github.com/nbuggia/Browser-View-Controller--iPhone-

第一步是对 UIApplication 进行子类化,这样您就可以覆盖谁可以对“openUrl”请求采取行动。该类可能如下所示:

#import <UIKit/UIKit.h>
#import "MyAppDelegate.h"

@interface MyApplication : UIApplication

-(BOOL)openURL:(NSURL *)url;

@end


@implementation MyApplication

-(BOOL)openURL:(NSURL *)url 
{
    BOOL couldWeOpenUrl = NO;

    NSString* scheme = [url.scheme lowercaseString];
    if([scheme compare:@"http"] == NSOrderedSame 
        || [scheme compare:@"https"] == NSOrderedSame)
    {
        // TODO - Update the cast below with the name of your AppDelegate
        couldWeOpenUrl = [(MyAppDelegate*)self.delegate openURL:url];
    }

    if(!couldWeOpenUrl)
    {
        return [super openURL:url];
    }
    else
    {
        return YES;
    }
}


@end

接下来,您需要更新 main.m 以指定MyApplication.h为 UIApplication 类的 bonified 委托。打开 main.m 并更改此行:

int retVal = UIApplicationMain(argc, argv, nil, nil);

对此

int retVal = UIApplicationMain(argc, argv, @"MyApplication", nil);

最后,您需要实现 [(MyAppDelegate*) openURL:url] 方法,让它对 URL 做任何您想做的事情。就像可能打开一个带有 UIWebView 的新视图控制器,并显示 URL。你可以这样做:

- (BOOL)openURL:(NSURL*)url
{
    BrowserViewController *bvc = [[BrowserViewController alloc] initWithUrls:url];
    [self.navigationController pushViewController:bvc animated:YES];
    [bvc release];

    return YES;
}

希望这对你有用。

于 2011-10-29T00:39:50.137 回答
3

假设你有以下实例,它们也被添加到你的 UIView 中:

UITextView *textView;
UIWebView *webView;

而textView包含URL字符串,可以将URL的内容加载到webView中,如下:

NSURL *url = [NSURL URLWithString:textView.text];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[webView loadRequest:req];
于 2009-10-12T16:01:05.407 回答