如何使UIWebView转到请求的URL

时间:2015-04-07 17:41:07

标签: ios objective-c uiwebview theos

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

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
    }

1 个答案:

答案 0 :(得分:0)

您可以做的是在顶部创建一个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];
}