I try to display a simple webpage inside my UIWebView without a Nib. The problem is when I click on my buttun a new page blanck page appear but nothing is display. Did I miss something?
- (void)loadView { UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; self.webView = web; NSString *urlAddress = @"http://www.google.com"; NSURL *url = [[[NSURL alloc] initWithString:urlAddress] autorelease]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; [webView loadRequest:requestObj]; [topView addSubview:self.webView]; [web release]; }
thank you,
If this is the exact code you're using then it can't work: the webView added to topView that is never put on screen anywhere.
You probably want to add the webView to the controller view, but a better place to do that might be viewDidLoad, where self.view can be used safely.
This code works for me:
- (void)viewDidLoad {
[super viewDidLoad];
self.webView = [[[UIWebView alloc]
initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease];
NSString *urlAddress = @"http://www.google.com";
NSURL *url = [[[NSURL alloc] initWithString:urlAddress] autorelease];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:requestObj];
[self.view addSubview:self.webView];
}
Using the Storyboard -
Step 1: Drag and drop a UIWebView in the View
Step 2: Then go to the .h file (for that particular view) and create an IBOutlet of a UIWebView. For example-
// MainViewController.h
@interface MainViewController : UIViewController
@property (nonatomic, strong) IBOutlet UIWebView *myWebView;
@end
Step 3: Go to the storyboard and create a connection from outlet, myWebView (This can be found in the inspector area of Xcode) to the UIWebView by doing a control drag.
Step 4: Now when we have the connection, we just need to go to the .m (for that particular view) and add the following code -
//MainViewController.m
@implementation MainViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlNameInString = @"https://www.google.com";
NSURL *url = [NSURL URLWithString:urlNameInString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[self.myWebView loadRequest:urlRequest];
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With