创建UIWebView并以编程方式加载网站

时间:2011-11-29 11:40:00

标签: iphone objective-c xcode uiwebview webview

以下是我的代码。我只是想加载一个网页并在屏幕上放一个后退按钮。不知道为什么屏幕上没有显示任何内容。

in .h

#import <UIKit/UIKit.h>
@interface ThirdViewController : UIViewController
{
    UIWebView *myWebView;
}
@property (nonatomic, retain) UIWebView *myWebView;
-(IBAction)goBack:(id)sender;
@end

in .m

#import "ThirdViewController.h"
@implementation ThirdViewController
@synthesize myWebView;
-(IBAction)goBack:(id)sender
{
    [myWebView goBack];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *urlAddress = @"http://www.apple.com";
    NSURL *url = [NSURL URLWithString:urlAddress];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [myWebView loadRequest:requestObj];
    [self.view addSubview:myWebView];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]     initWithTitle:@"Back"                                                                              style:UIBarButtonItemStylePlain                                                                         target:self action:@selector(goBack:)];
}

3 个答案:

答案 0 :(得分:34)

初始化您的webView。

UIWebView *tempWebview = [[UIWebView alloc]initWithFrame:theFrame];
NSString *urlAddress = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
self.myWebView = tempWebview;
[tempWebview loadRequest:requestObj];
[tempWebview release];
myWebView.delegate=self; 

答案 1 :(得分:2)

  

首先初始化Web视图。写下以下代码[Super   viewDidLoad中];和Nsstring Inisilization。

myWebView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
myWebView.delegate=self;
[self.view addSubview:myWebView]
  

然后加载请求您的代码将起作用。

答案 2 :(得分:0)

将以下代码添加到viewcontroller.m文件viewDidLoad方法中。

UIWebView *webView = [[UIWebView alloc]init];
NSString *urlString = @"http://www.sourcefreeze.com";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
[self.view addSubview:webView];

有关完整的uiwebview示例,请参阅以下链接。

http://sourcefreeze.com/ios-webview-uiwebview-example/