対象:
Objective-C

Web ViewでWebページを表示する

iOSでWeb ViewでWebページを表示するために必要な事は概ね以下になる。

  1. Interface BuilderでWeb Viewを貼り付ける
  2. Web Viewのアウトレットを作成
  3. Scales Page To Fitをチェックする
  4. loadRequestメソッドでWebページをロード

まずInterface BuilderでWeb Viewを貼り付ける。Web Viewのアウトレットを作成したら、Attibutes InspectorでScales Page To Fitをチェックする。


#import  <UIKit/UIKit.h>

@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

後はloadRequestメソッドで好きなWebページをロードするだけである。

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize webView;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [webView loadRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/jp/"]]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

また、Web Viewを使ってリモートのサーバにあるWebページだけでなく、ローカルにあるHTMLを表示することもできる。用意したHTMLは以下のようなものである。これをiphonelocal.htmlとして.mや.h等と同じフォルダに作成する。

<!DOCTYPE html>
<html lang="ja">
	<head>
		<meta charset="utf-8">
		<title>iPhoneでHTML表示</title>
	</head>
	<body>
		<h1>iPhoneでHTML表示</h1>
		<p>iPhoneのローカルHTMLを表示。</p>
	</body>
</html>

loadRequestメソッドを以下のように書き換えれば、ローカルに配置したiphonelocal.htmlを表示することができる。

    [webView loadRequest: [NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"iphonelocal" ofType:@"html"]]]];
(2013/10/17)

新着情報
【オープンソースソフトウェア環境構築】Apple silicon Macで開発環境を構築
【Rust Tips】Actix webでJSONをPOSTする
【Rust Tips】コマンドライン引数を取得する

Copyright© 2004-2019 モバイル開発系(K) All rights reserved.
[Home]