如何让 UIWebView 去请求 URL

How to make UIWebView go to requested URL

我正在构建一个浏览器应用程序,我有一个 UIWebView 和一个 textField 我需要知道我将在我的按钮中放入什么代码来使 URL 放在 textField 中显示在 UIWebView

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];   // x is width,y is hght


NSString *urlAddress =     @"http://www.livewiretech.co.nf/Web_app/Home.html";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];

[self.view addSubview:webView];

我有一个文本框

    // Create Text Field
    UITextField *myTextField = [[UITextField alloc]       initWithFrame:CGRectMake(10, 100, 200, 40)];
    [myTextField setBackgroundColor:[UIColor clearColor]];
    [myTextField setText:@"http://Www.url.com"];
    [[self view] addSubview:myTextField];
    [myTextField release];

这是我的按钮

    -(void) goButton {
    //code here
    }

您可以做的是在顶部创建一个 UITextField 和它旁边的一个 Go 按钮。让用户在 textField 中输入 URL 并按下 Go 按钮将 url 传递给 UIWebView loadRequest 方法。

您需要相应地调整 UI 以使 UITextField 位于 UIWebView

的顶部和下方

更新答案

将您的 UIWebView 初始化为 .h 文件中的 属性。

在您的 .h 文件中创建以下属性

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController {

}

@property (strong, nonatomic) UITextField *urlText;
@property (strong, nonatomic) UIWebView *webView;

@end

在您的 .m 文件中

-(void)viewDidLaod {
    self.urlText = [[UITextField alloc] initWithFrame:CGRectMake(0, 11, 229, 25)];
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,40, 300, 500)];    
    UIButton *goButton = [UIButton buttonWithType:UIButtonTypeCustom];
    goButton.frame = CGRectMake(235, 11, 25, 25);
    [goButton setTitle:@"GO" forState:UIControlStateNormal];
    [goButton addTarget:self action:@selector(goButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubView:self.urlText];
    [self.view addSubView:goButton];
    [self.view addSubview:self.webView];
 }



-(void)goButton:(id)sender {
 NSString *urlAddress = self.urlText.text;
 NSURL *url = [NSURL    URLWithString:urlAddress];   
 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
 [self.webView loadRequest:request];
}