系統的 UIAlertView 樣式固定,很難貼合設計稿。其中一種做法是乾脆自己開一扇 window 當彈窗——因為 window 的層級可以設定到最高,天然就能蓋在任何畫面之上。
// // ABCustomAlertView.h // #import <UIKit/UIKit.h> @interface ABCustomAlertView : UIWindow // 顯示 - (void)show; // 消失 - (void)dismiss; @end
對外只給兩個方法,其餘的版面配置全部封裝在實作檔裡,呼叫端只要 show 與 dismiss 就好。
//
// ABCustomAlertView.m
//
#import "ABCustomAlertView.h"
@implementation ABCustomAlertView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 讓彈窗蓋在一般內容之上
self.windowLevel = UIWindowLevelAlert;
// 這裡不能直接設 UIWindow 的 alpha,
// 否則會連子 view 一起變透明;
// 改用一張半透明底圖來做遮罩
self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"alert_bg.png"]];
UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 80)] autorelease];
view.backgroundColor = [UIColor blackColor];
view.center = CGPointMake(160, 240);
[self addSubview:view];
}
return self;
}
- (void)show {
[self makeKeyAndVisible];
}
- (void)dismiss {
[self resignKeyWindow];
[self release];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 點擊畫面任意處即可關閉
[self dismiss];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
}
@end
UIWindowLevelAlert,確保彈窗永遠浮在最上層,不受一般畫面切換影響。alpha 會讓所有子視圖一起變淡,因此改用半透明底圖(或自訂 view 的 backgroundColor alpha)來做遮罩。touchesBegan: 就能攔下背景點擊,實作「點空白處關閉」。dismiss 中搭配 release 成對使用;若專案啟用 ARC,請移除手動 release。這只是最基礎的骨架。實務上通常還會加上淡入淡出動畫、block 回呼(點擊確認/取消時通知呼叫方)、以及點擊彈窗本身不關閉的判斷。把自訂的 UI 元件與 delegate 接上去,就能得到一個完全可控的彈窗。