2012-09-25 43 views
20

Tôi đã thử cách này một lúc, nhưng tôi không hiểu đúng.Tạo UIWebView theo chương trình

Tôi đã viết hàm init sau đây trong một tập tin hỗ trợ:

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
    webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 1024,768)]; 
} 
    return self; 
} 

và sau trong ViewController.m

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    UIWebView *view = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)]; 
    NSString *[email protected]"http://www.google.com"; 
    NSURL *nsurl=[NSURL URLWithString:url]; 
    NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl]; 
    [view loadRequest:nsrequest]; 
} 

Tôi cũng đã cố gắng tạo ra webview trong didFinishLaunchingWithOptions: phương pháp appdelegate, nhưng nó cũng không hoạt động.

Cách chính xác là gì?

Trả lời

4

Dường như bạn đã quên thêm webview như là một subview nhìn mẹ:

-(id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 1024,768)]; 
     [self addSubview:webview]; 
    } 
    return self; 
} 

Cũng viewDidLoad không phải là nơi thích hợp để tạo subviews. Bạn nên tiếp xúc với webview như một tài sản của quan điểm của bạn, và sau đó truy cập nó từ viewDidLoad, như thế này:

NSString *[email protected]"http://www.google.com"; 
NSURL *nsurl=[NSURL URLWithString:url]; 
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl]; 
[[self.view webview] loadRequest:nsrequest]; 
+0

nhờ trả lời của bạn, nhưng im nhận được lỗi trên self.view – user1153798

+0

@ user1153798 nếu mã là trong 'UIViewController',' self.view' nên khỏe. '.view' có thể sai - hãy thử' [self.view webview] 'thay vào đó (xem phần chỉnh sửa). – dasblinkenlight

31

tôi hy vọng giải pháp này sẽ giúp bạn.

Chỉ cần thêm những dòng này trong - (void)viewDidLoad

UIWebView *webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 1024,768)]; 
    NSString *[email protected]"http://www.google.com"; 
    NSURL *nsurl=[NSURL URLWithString:url]; 
    NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl]; 
    [webview loadRequest:nsrequest]; 
    [self.view addSubview:webview]; 

Ở đây tôi sử dụng khung tĩnh của xem web, bạn có thể sử dụng theo yêu cầu của bạn.

+0

Tôi đã sử dụng khung tĩnh của chế độ xem web, bạn có thể sử dụng theo yêu cầu của mình. – iBapu

0
UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 568)]; 
webView.delegate = self; 
NSString *[email protected]"http://www.google.com"; 
NSURL *nsurl=[NSURL URLWithString:url]; 
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl]; 
[webview loadRequest:nsrequest]; 
[self.view addSubview:webview]; 

Khai UIWebviewDelegate trong giao diện của viewController

Các vấn đề liên quan