.h および .m ファイルのコードは次のとおりです。
XIB を作成し、その上に UIWebView を置き、クラスにバインドします。
ヘッダファイル用
#import <UIKit/UIKit.h>
@interface NewWebViewController : UIViewController<UIWebViewDelegate> {
IBOutlet UIWebView *webView;
NSString *currentURL;
UIActivityIndicatorView *activityView;
}
@property (nonatomic, copy) NSString *currentURL;
@property (nonatomic, retain) UIActivityIndicatorView *activityView;
@end
実装ファイル (.m) の場合
#import "NewWebViewController.h"
@interface NewWebViewController ()
@end
@implementation NewWebViewController
@synthesize currentURL;
@synthesize activityView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
webView.frame = self.view.frame;
[webView setScalesPageToFit:YES];
NSURL *url = [NSURL URLWithString:self.currentURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
self.activityView = [[[UIActivityIndicatorView alloc] init] autorelease];
self.activityView.tag = 1;
self.activityView.hidesWhenStopped = YES;
UIView *customView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)] autorelease];
self.activityView.center = customView.center;
[customView addSubview:self.activityView];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:customView] autorelease];
[self.activityView startAnimating];
}
#pragma mark UIWebView Delegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
[self.activityView startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[self.activityView stopAnimating];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(@"Error %@",[error description]);
[self.activityView stopAnimating];
}
- (void)viewDidUnload
{
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
[webView stopLoading];
webView.delegate = nil;
webView = nil;
self.activityView = nil;
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
webView.frame = self.view.frame;
return YES;//(interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void) dealloc {
[currentURL release];
[webView release];
[super dealloc];
}
@end
使い方はこちら
- (void) openWebViewControllerWithURL:(NSString*) url {
if (!url) {
return;
}
NewWebViewController *vController = [[NewWebViewController alloc] initWithNibName:@"NewWebViewController" bundle:nil];
vController.currentURL = url;
[self.navigationController pushViewController:vController animated:YES];
[vController release];
}
ボタンをクリックすると、ロードしたい URL を渡すだけです
このような
[self openWebViewControllerWithURL:@"http://www.google.com"];