萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS UIActionSheet 與 Toolbar/TabBar 共存的正確呈現方式

經典問題: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

現代替代:UIAlertController (iOS 8+)

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 永遠在可見、可點擊的位置彈出。

copyright © 萬盛學電腦網 all rights reserved