在 iOS 早期版本中,UIActionSheet 是最常用的底部動作選單元件,特別適合放在「刪除資料」「清空緩存」這類需要使用者二次確認的場景。本文以一個「點擊畫面任意處即彈出清空圖片緩存確認框」的小範例,說明它的基本用法。
使用者用手指觸碰畫面上的任何位置,畫面底部就會滑出一個動作表,標題為「確定要清空圖片緩存?」,並提供「確定」與「取消」兩個選項。

這個範例刻意把觸發條件寫在 touchesBegan:withEvent: 裡,這樣就不必額外配置任何按鈕,只要點擊視圖就能喚出動作表:
// 點擊畫面任意處,彈出 UIActionSheet
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"確定要清空圖片緩存?"
delegate:self
cancelButtonTitle:@"取消"
destructiveButtonTitle:@"確定"
otherButtonTitles:nil, nil];
[sheet showInView:self.view];
}
initWithTitle:delegate:cancelButtonTitle:destructiveButtonTitle:otherButtonTitles: 這幾個參數各有分工:
nil 結束。光是彈出選單還不夠,真正「清空緩存」的動作要寫在回呼方法裡。讓類別遵循 UIActionSheetDelegate 協定,並實作:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == actionSheet.cancelButtonIndex) {
return; // 使用者按了取消
}
if (buttonIndex == actionSheet.destructiveButtonIndex) {
// 在這裡執行清除快取的邏輯
}
}
使用 destructiveButtonIndex 與 cancelButtonIndex 這兩個唯讀屬性來判斷,比硬寫數字索引安全得多,因為即使日後調整了選單項目順序,判斷邏輯也不會出錯。另外要留意,這套 API 從 iOS 8 起已被 UIAlertController 取代,新專案建議改用 UIAlertControllerStyleActionSheet;此範例保留下來,主要是為了說明舊專案維護時常見的寫法。