10

カスタム ビューをナビゲーション ビューに配置するナビゲーション ベースのアプリケーションがあります。

まず、「ナビゲーション ビュー」のフレームを取得して、カスタム ビューを適切に配置できるようにする方法を知りたいです。
また、ナビゲーション バーを非表示にして、フレーム情報を正しく取得したい場合もあります。( [[UIScreen mainScreen] 境界] ではありません)

第二に、一般的に、スーパービューのフレームにアクセスして、それに応じてビューを配置するにはどうすればよいですか?
次のことを試しましたが、成功しませんでした。

-(void) loadView {
[super loadView];
UIView* myView = [[UIView alloc] initWithFrame: CGRectZero];
self.view = myView;
self.view.frame = self.view.superview.frame;
[myView release];
}

またはlayoutSubviewsでフレームを設定しましたが、layoutSubviewsが呼び出されていないことに気付きました。この特定のビューにサブビューがないためだと思いますか?

ありがとうございました

-編集-

与えられた答えで、view.frameをスーパービューの境界に設定する必要があることがわかりました。
問題は、viewDidLoad 内のスーパービューにアクセスできないことです。
スーパービューはviewWillAppearでは正しく設定されていますが、viewDidLoadでは設定されていません。

pushViewController によってプッシュされたときや self.view
にアクセスしたときなど、viewDidLoad がさまざまな時点で呼び出されることがわかりました。次のコードがあり、viewDidLoad は nil == controller.view.superview から呼び出されます。

if (nil == controller.view.superview) {
    CGRect frame = scrollView.frame;
    frame.origin.x = frame.size.width * page;
    frame.origin.y = 0;
    controller.view.frame = frame;
    [scrollView addSubview:controller.view];
}

viewDidLoad からスーパービューにアクセスできないため、以前に viewDidLoad で行ったようにビューをレイアウトできません。これはとても不便で、不必要に複雑に思えます。
何か提案はありますか?

4

2 に答える 2

10

The superview property is nil until your view is added as a subview somewhere. In general, you can't know what the superview will be within the loadView method.

You could use autoresizing properties, as suggested by Costique. Check out the Resizing Subviews in the official UIView docs.

You could also set the frame after the call to loadView, for example in something like this:

MyViewController *myController = [[MyViewController alloc] init];
myController.view.frame = window.bounds;
[window addSubview:myController.view];

By the way, it is generally safer to use the parent's bounds property for the frame of the subview. This is because a parent's bounds are in the same coordinate system as the subview's frame, but the parent's frame may be different. For example:

UIView *parentView = /* set up this view */;
UIView *subView = /* set up subview */;
[parentView addSubview:subView];
parentView.frame = CGRectMake(30, 50, 10, 10);
subView.frame = subView.superview.frame;  // BAD!!!
// Right now subView's offset is (30, 50) within parentView.
subView.frame = subView.superview.bounds;  // Better.
// Now subView is in the same position/size as its parent.
于 2010-11-09T06:14:42.763 に答える
7

自動サイズ変更マスクを設定するだけで、あとはナビゲーション コントローラーが行います。

myView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
于 2010-11-09T05:54:44.193 に答える