2008年12月24日水曜日

UIDatePickerの回転うまくいきました。

昨日、「UIDatePickerをうまく回転できない」という記事を書きましたが、あれこれ試行錯誤した結果、以下の方法で、ちゃんと回転できることが分かりました。

まず、以下のように、willRotateToInterfaceOrientation(回転しようとしているタイミング)で、画面に表示されているUIDatePickerを、一旦、親のビューから削除し、インスタンスをリリースします。

- (void)willRotateToInterfaceOrientation:
(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration {
[datePicker removeFromSuperview];
[datePicker release];
}

そして、didRotateFromInterfaceOrientation(回転が終わったタイミング)で、表示したい位置とサイズを指定してUIDatePickerのインスタンスを生成して、画面のサブビューとして追加すればOKのようです。

- (void)didRotateFromInterfaceOrientation:
(UIInterfaceOrientation)fromInterfaceOrientation {
CGRect frame;
// 縦から横に回転した場合
if (fromInterfaceOrientation ==
UIInterfaceOrientationPortrait) {
frame = CGRectMake(0, 88, 480, 180);
}
// 横から縦に回転した場合
else {
frame = CGRectMake(0, 200, 320, 216);
}
datePicker = [[UIDatePicker alloc] initWithFrame:frame];
// 必要に応じて、属性を設定する...
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.locale = [NSLocale currentLocale];
datePicker.timeZone = [NSTimeZone defaultTimeZone];
datePicker.date = ...
...
[self.view addSubview:datePicker];
}

なお、この記事では、例として、willRotateToInterfaceOrientationのタイミングで、UIDatePickerを、一旦、親のビューから削除して、インスタンスをリリースするように記載していますが、didRotateFromInterfaceOrientationでやっても、結果としては、同じようにちゃんと回転されます。回転時の見た目が若干違うので、どちらのタイミングで処理するかは、実装者の好みで決めていいのかな、と思います。

0 コメント:

コメントを投稿