所謂模態窗口,就是當這個窗口彈出的時候,只能在這個窗口上進行操作,並且只有操作完這個窗口之后,才能繼續操作之前的視圖。AlertView就是一個例子,當UIAlertView彈出之后,原先的視圖全部失去響應,只有當點擊了UIAlertView的按鈕之后,才能對原先的視圖恢復操作。要實現模態窗口有兩種方法:
- 使用系統自帶的模態彈出,通過
presentModalViewController:controller animated:YES(NO)
方法彈出一個對話框。 - 我們根據模態窗口的特點,自己手動實現。
先說第一種:[presenModalViewController:Animated:] :
第一種很簡單,只需實例化想要模態彈出的ViewController,然后自身調用[presentModalViewController:nextViewController animated:YES],實例代碼:
- 為FirstViewController定義一個UIButton並關聯touch up inside事件:
-(IBAction)btnClicked:(id)sender
{
LZSecondVC *secondVC = [[LZSecondVC alloc] init];
[self presentModalViewController:secondVC animated:YES];
[secondVC release];
}
- 同樣也為SecondViewController定義一個UIButton關聯點擊事件,調用[dismissModalViewControllerAnimated:]方法即可回到之前的頁面-(IBAction)btnClicked:(id)sender
{
[selfdismissModalViewControllerAnimated:YES];
}
就是這么簡單! 但是有一個問題,如果我們用了UINavigationController,並且跳了好幾個頁面,在使用這種彈出的時候就會出現一個比較詭異的問題,不能橫屏!效果如下。
如圖,這是我做的一個點菜系統中的一個菜單,我使用上文介紹的模態窗口顯示出這個視圖,但是出現了,這樣的一幕,不能橫屏。解決方法很簡單,找到入口類里的的VIewController,並通過入口類的ViewController調用[self presentModalViewController:secondVC animated:YES];即可。代碼如下:
-(IBAction)showMyOrder:(id)sender
{
//實例化模態彈出的ViewController
LZOrderDishMenuViewController *myOrderMenu = [[LZOrderDishMenuViewControlleralloc] init];
//設置彈出時的動畫類型
myOrderMenu.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//找到入口類
OrderMenuAppDelegate *appDelegate = [[UIApplicationsharedApplication] delegate];
//通過入口類的ViewController調用present方法
[appDelegate.currentViewControllerpresentModalViewController:myOrderMenu animated:YES];
[myOrderMenu release];
}
修改過代碼之后的效果,可以看到,問題已經解決。
--------------------------------------------------------------------------第二種方式--------------------------------------------------------------------------------------------
第二種也很簡單,特別是iPad開發經常用到,在屏幕中間彈出一個小的View,當這個小View存在時,底部的所有的可交互控件都不得響應用戶操作,如果控件比較少,在小View彈出的時候將底部可交互控件的enable屬性設置為NO。如果控件較多,在View之前加一個與屏幕大小一樣的View覆蓋住底部的所有控件即可,這樣就可以截獲所有的用戶操作。效果如下:
dismissModalViewControllerAnimated: