2012-09-25 29 views
20

Ci sto provando da un po ', ma non ho capito bene.Creazione di UIWebView a livello di programmazione

Ho scritto la seguente funzione init in un file di supporto:

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

e seguendo 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]; 
} 

Ho anche cercato di creare la WebView in didFinishLaunchingWithOptions: metodo AppDelegate, ma anche non ha funzionato.

Qual è il modo corretto?

risposta

4

Sembra che si è dimenticato di aggiungere webview come una visualizzazione secondaria della sua vista padre:

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

anche viewDidLoad non è il posto giusto per creare subviews. Si dovrebbe esporre webview come una proprietà della visualizzazione, e quindi accedervi da viewDidLoad, in questo modo:

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

grazie per la risposta, ma nel mese di ottenere errore self.view – user1153798

+0

@ user1153798 se il codice è in 'UIViewController',' self.view' dovrebbero essere bene. '.view' potrebbe essere sbagliato - prova invece' [self.view webview] '(vedi la modifica). – dasblinkenlight

31

Spero che questa soluzione vi aiuterà.

Basta aggiungere queste righe in - (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]; 

Qui ho usato cornice di vista statico web, è possibile utilizzare in base vostro requisito.

+0

Ho usato il frame statico della vista Web, è possibile utilizzare in base alle proprie esigenze. – 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]; 

Dichiarare UIWebviewDelegate nell'interfaccia del viewcontroller

Problemi correlati