Linux で iPhone ツールチェーンを使用しているため、Interface Builder はありません。では、ViewController サブクラスでビューをレイアウトするにはどうすればよいでしょうか? たとえば、画面の中央に UITextView が必要ですか? loadView
またはでこれを行う必要がありますviewDidLoad
。ViewController サブクラスのビューもそれ自体に設定する必要がありますか?
3 に答える
コードを使用してすべてのビューをレイアウトするのは簡単なことではありません。ここにいくつかのコードがあります:
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake (100, 100, 100, 100)];
[self.view addSubview:textView];
フレームは場所 (1 番目と 2 番目の引数は x と y コーディネーター) とサイズ (3 番目と 4 番目の引数はテキスト ビューの幅と高さ) です。
この方法を使用すると、任意のビューをクラスに追加できます。一部のビューは組み込まれており、自分で描画する必要はありません。一部はそうではなく、UIView をサブクラス化し、drawRect をオーバーライドする必要があります。
メインView Controllerのロードが完了したら、viewDidLoadでこれを行う必要があります
通常、ビュー階層全体を loadView メソッドで構築し、viewDidLoad で追加のセットアップを実行します。たとえば、ビュー コントローラーに関連付けられたデータを反映するようにサブビューのコンテンツをセットアップします。重要なことは、loadView メソッドでビュー コントローラーのビューアウトレットを設定することです。
@synthesize label; // @property(nonatomic,retain) UILabel *label declared in the interface.
-(void)loadView {
// Origin's y is 20 to take the status bar into account, height is 460 for the very same reason.
UIView *aView = [[UIView alloc]initWithFrame:CGRectMake(0,20,320,460)];
[aView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
[aView setAutoresizeSubviews:YES];
// The 150x50 label will appear in the middle of the view.
UILabel *aLabel = [[UILabel alloc]initWithFrame:CGRectMake((320-150)/2,(460-50)/250,150,50)];
// Label will maintain the distance from the bottom and right margin upon rotation.
[aLabel setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin];
// Add the label to the view hiearchy.
[self setLabel:aLabel];
[aView addSubview:aLabel];
// Set aView outlet to be the outlet for this view controller. This is critical.
[self setView:aView];
// Cleanup.
[aLabel release];
[aView release];
}
-(void)viewDidLoad {
// Additional and conditional setup.
// labelText is an istance variable that hold the current text for the label. This way, if you
// change the label text at runtime, you will be able to restore its value if the view has been
// unloaded because of a memory warning.
NSString *text = [self labelText];
[label setText:text];
}
-(void)viewDidUnload {
// The superclass implementation will release the view outlet.
[super viewDidUnload];
// Set the label to nil.
[self setLabel:nil];
}
おそらく最大の困難は、自動サイズ変更マスクなど、IB 設定が UIView 変数およびメソッドにどのようにマップされるかを理解することです。Apple の UIView および UIViewController クラス リファレンスには、役立つ情報が満載です。