經典問題:UIActionSheet 在包含 Toolbar 或 TabBar 的頁面上用 showInView: 會被底部條遮擋,導致按鈕不可點擊。解決方案是使用專門的呈現方法綁定到容器視圖。
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"選項"
delegate:self
cancelButtonTitle:@"取消"
destructiveButtonTitle:nil
otherButtonTitles:@"選項一", @"選項二", nil];
// ❌ 錯誤:在有 TabBar/Toolbar 的視圖上調用
[sheet showInView:self.view]; // 底部按鈕被 TabBar 遮擋,無法響應點擊
// ✅ 有 Toolbar 時
[sheet showFromToolbar:self.toolbar];
// ✅ 有 TabBar 時(控制器內)
[sheet showFromTabBar:self.tabBarController.tabBar];
// ✅ 通用:從導航欄按鈕彈出(iPad 彈出框模式)
[sheet showFromBarButtonItem:self.navigationItem.rightBarButtonItem animated:YES];
| 方法 | 定位參考 | 適用場景 | iPad 行為 |
|---|---|---|---|
showInView: | 指定 View 坐標系 | 無底部條的純內容視圖 | 全屏彈出(居中) |
showFromToolbar: | Toolbar 框架 | 頂部/底部 Toolbar 界面 | 從 Toolbar 彈出 Popover |
showFromTabBar: | TabBar 框架 | TabBarController 管理的頁面 | 從 TabBar 彈出 Popover |
showFromBarButtonItem: | BarButtonItem 位置 | 導航欄/工具欄按鈕觸發 | 從按鈕彈出 Popover |
showFromRect:inView:animated: | 指定 Rect 在 View 中 | 自定義錨點位置 | 從 Rect 彈出 Popover |
UIActionSheet 已棄用,統一遷移至 UIAlertController:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"選項"
message:nil
preferredStyle:UIAlertControllerStyleActionSheet];
[alert addAction:[UIAlertAction actionWithTitle:@"選項一" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
// 處理
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
// iPad 必須設置 popoverPresentationController
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
alert.popoverPresentationController.sourceView = self.view;
alert.popoverPresentationController.sourceRect = sender.frame; // 或 barButtonItem
alert.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
}
[self presentViewController:alert animated:YES completion:nil];
拖入圖片到 Xcode 專案時,勾選 「Copy items if needed」 確保資源複製到項目目錄,而非僅建立引用(源文件移動會導致丟失)。
掌握正確呈現方式,讓 ActionSheet 永遠在可見、可點擊的位置彈出。