如何在UI Web View中打开UITextView URL?

san*_*ndy 5 iphone url uiwebview uitextview

在我的iPhone应用程序中,UITextView包含一个URL.我想在UIWebView中打开此URL而不是将其打开到safari中?我的UITextView包含一些数据和URL.在某些情况下,没有.URL可以不止一个.

谢谢桑迪

Man*_*Mal 10

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

  1. 勾选UITextView从Xib或Storyboard获取的以下属性.

检查UITextView的这些属性

或者为动态采取的textview写下这些.

textview.delegate=self;
textview.selectable=YES;
textView.dataDetectorTypes = UIDataDetectorTypeLink;
Run Code Online (Sandbox Code Playgroud)
  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;
}
Run Code Online (Sandbox Code Playgroud)

我想你正在寻找那个.


Nat*_*gia 9

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

myTextView.dataDetectorTypes = UIDataDetectorTypeLink;
Run Code Online (Sandbox Code Playgroud)

然后,您需要配置您的应用程序以捕获此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
Run Code Online (Sandbox Code Playgroud)

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

int retVal = UIApplicationMain(argc, argv, nil, nil);
Run Code Online (Sandbox Code Playgroud)

对此

int retVal = UIApplicationMain(argc, argv, @"MyApplication", nil);
Run Code Online (Sandbox Code Playgroud)

最后,您需要实现[(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;
}
Run Code Online (Sandbox Code Playgroud)

希望这对你有用.


pyt*_*ick 3

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

UITextView *textView;
UIWebView *webView;
Run Code Online (Sandbox Code Playgroud)

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

NSURL *url = [NSURL URLWithString:textView.text];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[webView loadRequest:req];
Run Code Online (Sandbox Code Playgroud)