Amazon

2011年7月2日土曜日

[iPhoneアプリ開発]画像表示サンプルコード

iOSアプリで画像を表示するためのサンプルソースコード

手順を以下に示します。

1. Xcodeの新規プロジェクトの作成でView-based Applicationを選択
2. プロジェクト名は適当に(image)
3. Classesフォルダの中にimageViewController.h, imageViewController.mが自動で作られているので、以下で置き換える
----- imageViewController.h -----

#import <UIKit/UIKit.h>

@interface imageViewController : UIViewController {
    IBOutlet UIImageView *imageView;
}
@property (nonatomic,retain)UIImageView *imageView;
@end

----- imageViewController.m -----
#import "imageViewController.h"

@implementation imageViewController
@synthesize imageView;
- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *url = [NSURL URLWithString:@"http://www.hoge.com/hoge.png";];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [[UIImage alloc] initWithData:data];
    imageView.image = image;
}

- (void)dealloc { 
    [imageView release];
    [super dealloc];
}
@end

4. ResourcesフォルダのimageViewController.xibをダブルクリック
5. imageViewController.xibフォルダの中のviewをダブルクリックして背景がグレーのウィンドウを表示
6. メニューバーのtoolsからLibraryを選択し、Libraryウィンドウから"Image View"を上記のグレーのウィンドウ(view)にドラッグ&ドロップ
7. メニューバーのtoolsからInspectorを選択し、Inspectorが表示されたらimageViewController.xibフォルダの中のFile's ownerを選択する
8. Inspectorの上部左から2番目のタブのConnectionsを開き、Outletsの中から"imageView"の右にある+をドラッグしてviewウィンドウのUIImageViewと表示されている部分へドロップする
9. imageViewController.xibへの変更を保存する(command+s)
10. Xcodeに戻り"ビルドと実行"をクリックすれば、シュミレーターが立ち上がり画像が表示される


ポイントは
  • Xcodeではロジックを定義
  • Interface Builderではビューを定義
  • XcodeのロジックとInterface Builderでのビューを紐づけるためにimageViewController.hの変数宣言においてIBOutletという型で変数を宣言することでInterface BuilderのFile's owner(imageViewControllerクラス)のConnectionsビューに宣言した変数がリストされて、それを配置したImageViewなどの部品と紐づけている

0 件のコメント:

コメントを投稿

Amazon3