Objective-C: 画面に画像を追加する
xibを使わずに動的に画面に画像を追加する方法です。
基本的にはいつも同じことをするので関数にしておくと便利です。
- (void)addImg:(NSString*)imgUri:(int)theX:(int)theY:(int)theW:(int)theH{ UIImageView* theImg = [[UIImageView alloc] init]; // 初期化 theImg.image = [UIImage imageNamed:imgUri]; // 画像のURIをimageに [theImg setFrame:CGRectMake(theX, theY, theW, theH)]; // x,y,幅,高さ [self.view addSubview:theImg]; // 画像を画面に追加 } - (void)viewDidLoad{ [super viewDidLoad]; [self addImg:@"hoge.png",50,150,100,200]; }
書いてて気付きましたが、この場合後から画像を変更したり位置を変更したりで不便かもです。
viewController.h
UIImageView* theImg[100]; // 要素数も動的な方がクールですが煩雑になりそうなので一旦これで。
viewController.m
int inc = 0; // 画像配列用の変数 - (void)addImg:(NSString*)imgUri:(int)theX:(int)theY:(int)theW:(int)theH{ theImg[inc] = [[UIImageView alloc] init]; // 初期化 theImg[inc].image = [UIImage imageNamed:imgUri]; // 画像のURIをimageに [theImg[inc] setFrame:CGRectMake(theX, theY, theW, theH)]; // x,y,幅,高さ [self.view addSubview:theImg[inc++]]; // 画像を画面に追加 } theImg[inc]
これで画像を後からの変更を行える形で追加出来ました。
詳細! Objective-C iPhoneアプリ開発 入門ノート
- 作者: 大重美幸
- 出版社/メーカー: ソーテック社
- 発売日: 2013/07/20
- メディア: 単行本
- この商品を含むブログを見る