系統的 UIAlertView 只能放文字,一旦想在彈窗裡塞輸入框、日期選擇器或自訂版面就會卡住。以下實作一個繼承自 UIView 的自定義版本,支援標題圖片加文字、可嵌入任意子視圖,最多兩個按鈕。
CustomAlertView *alertView = [[CustomAlertView alloc] initWithTitle:@"提示"
message:@"dylan_lwb_"
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
// [alertView addCustomerSubview:myView]; // 在訊息區加入自定義視圖
[alertView show];
[alertView release];
#pragma mark - 代理方法
- (void)alertView:(CustomAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
}
- (void)alertViewClosed:(CustomAlertView *)alertView {
}
- (void)willPresentCustomAlertView:(UIView *)alertView {
}
在專案中新增 CustomAlertView 類別(繼承 UIView),貼入以下程式碼:
#if defined(__APPLE_CC__) && (__APPLE_CC__ >= 5549)
#define NS_REQUIRES_NIL_TERMINATION __attribute__((sentinel(0,1)))
#else
#define NS_REQUIRES_NIL_TERMINATION __attribute__((sentinel))
#endif
#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height
#define RGBA_COLOR(r, g, b, a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#define kBCAlertViewPresentNotify @"kBCAlertViewPresentNotify"
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@class CustomAlertView;
@protocol MBAlertViewDelegate <NSObject>
@optional
- (void)alertView:(CustomAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
- (void)alertViewClosed:(CustomAlertView *)alertView;
- (void)willPresentCustomAlertView:(UIView *)alertView;
- (void)hideCurrentKeyBoard;
@end
@interface CustomAlertView : UIView
@property (nonatomic, assign) id <MBAlertViewDelegate> delegate;
@property (nonatomic, assign) BOOL isNeedCloseBtn; // 左上角叉叉按鈕
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *message;
@property (nonatomic, retain) UIView *backView;
@property (nonatomic, retain) UIView *titleBackgroundView;
@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, retain) UIImageView *titleIcon;
@property (nonatomic, retain) NSMutableArray *customerViewsToBeAdd;
- (id)initWithTitle:(NSString *)title
message:(NSString *)message
delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;
- (void)initTitle:(NSString *)title
message:(NSString *)message
delegate:(id)del
cancelButtonTitle:(NSString *)cancelBtnTitle
otherButtonTitles:(NSString *)otherBtnTitles, ... NS_REQUIRES_NIL_TERMINATION;
- (void)show;
- (void)addCustomerSubview:(UIView *)view;
+ (void)exChangeOut:(UIView *)changeOutView dur:(CFTimeInterval)dur;
+ (CustomAlertView *)defaultAlert;
@end
布局全集中在 layoutSubviews 中,每次顯示前先清掉舊的子視圖再重建,避免重複呼叫 show 時元件疊加。
#import "CustomAlertView.h"
@interface CustomAlertView ()
{
BOOL _isShow;
}
@property (nonatomic, retain) NSString *cancelButtonTitle;
@property (nonatomic, retain) NSMutableArray *otherButtonTitles;
@end
@implementation CustomAlertView
static const CGFloat mWidth = 290;
static const CGFloat mHeight = 180;
static const CGFloat mMaxHeight = 250;
static const CGFloat mBtnHeight = 30;
static const CGFloat mBtnWidth = 110;
static const CGFloat mHeaderHeight = 40;
+ (CustomAlertView *)defaultAlert {
static CustomAlertView *shareCenter = nil;
if (!shareCenter) {
shareCenter = [[CustomAlertView alloc] init];
}
return shareCenter;
}
- (NSMutableArray *)customerViewsToBeAdd {
if (_customerViewsToBeAdd == nil) {
_customerViewsToBeAdd = [[NSMutableArray alloc] init];
}
return _customerViewsToBeAdd;
}
- (id)init {
self = [super initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT + 20)];
if (self) {
_isShow = NO;
}
return self;
}
#pragma mark - 初始化並接收可變參數
- (id)initWithTitle:(NSString *)title
message:(NSString *)message
delegate:(id)del
cancelButtonTitle:(NSString *)cancelBtnTitle
otherButtonTitles:(NSString *)otherBtnTitles, ... {
self = [super initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT + 20)];
if (self) {
self.delegate = del;
self.cancelButtonTitle = cancelBtnTitle;
self.isNeedCloseBtn = NO;
va_list argList;
if (otherBtnTitles) {
self.otherButtonTitles = [NSMutableArray array];
[self.otherButtonTitles addObject:otherBtnTitles];
}
va_start(argList, otherBtnTitles);
id arg;
while ((arg = va_arg(argList, id))) {
[self.otherButtonTitles addObject:arg];
}
va_end(argList);
self.title = title;
self.message = message;
}
return self;
}
#pragma mark - 版面配置
- (void)layoutSubviews {
[super layoutSubviews];
for (UIView *view in [self subviews]) {
[view removeFromSuperview];
}
// 半透明遮罩
UIView *bgView = [[UIView alloc] initWithFrame:self.frame];
[bgView setBackgroundColor:[UIColor blackColor]];
[bgView setAlpha:0.4];
[self addSubview:bgView];
[bgView release];
// 彈窗本體
if (!_backView) {
_backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mWidth, mHeight)];
_backView.opaque = NO;
_backView.backgroundColor = [UIColor whiteColor];
_backView.layer.shadowOffset = CGSizeMake(1, 1);
_backView.layer.shadowRadius = 2.0;
_backView.layer.shadowColor = [UIColor grayColor].CGColor;
_backView.layer.shadowOpacity = 0.8;
[_backView.layer setMasksToBounds:NO];
}
[self setupHeaderView]; // 標題區:圖片 + 文字
[self setupMessageView]; // 訊息區:文字或自定義子視圖
[self setupButtonView]; // 按鈕區:一個或兩個
UIControl *touchView = [[UIControl alloc] initWithFrame:self.frame];
[touchView addTarget:self action:@selector(touchViewClickDown)
forControlEvents:UIControlEventTouchDown];
[self addSubview:touchView];
[touchView release];
_backView.center = self.center;
[self addSubview:_backView];
if (!_isShow) {
[CustomAlertView exChangeOut:_backView dur:0.5];
}
if (self.delegate &&
[self.delegate respondsToSelector:@selector(willPresentCustomAlertView:)]) {
[self.delegate willPresentCustomAlertView:self];
}
[[NSNotificationCenter defaultCenter] postNotificationName:kBCAlertViewPresentNotify
object:nil userInfo:nil];
}
#pragma mark - 標題區
- (void)setupHeaderView {
UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mWidth, mHeaderHeight)];
titleView.backgroundColor = RGBA_COLOR(36, 193, 64, 1);
CGSize titleSize = CGSizeZero;
if (self.title && [self.title length] > 0) {
titleSize = [self.title sizeWithFont:[UIFont fontWithName:@"Helvetica-Bold" size:18.0f]];
}
if (titleSize.width > 0) {
// 標題圖片
CGFloat startX = (titleView.frame.size.width - 40 - titleSize.width) / 2;
UIImageView *titleImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xxxxx.png"]];
titleImage.frame = CGRectMake(startX, (titleView.frame.size.height - 30) / 2, 30, 30);
self.titleIcon = titleImage;
[titleView addSubview:titleImage];
[titleImage release];
startX += 40;
// 標題文字(過長時退縮)
UILabel *titleLabel = [[UILabel alloc]
initWithFrame:CGRectMake(startX, (titleView.frame.size.height - 20) / 2,
titleSize.width, 20)];
if (titleLabel.frame.size.width > 250) {
titleLabel.frame = CGRectMake(50, (titleView.frame.size.height - 20) / 2, mWidth - 60, 20);
titleImage.frame = CGRectMake(5, (titleView.frame.size.height - 30) / 2, 30, 30);
}
titleLabel.text = self.title;
titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:18.0f];
titleLabel.textColor = [UIColor whiteColor];
titleLabel.backgroundColor = [UIColor clearColor];
self.titleLabel = titleLabel;
[titleView addSubview:titleLabel];
[titleLabel release];
} else {
UIImageView *titleImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xxxxx.png"]];
titleImage.frame = CGRectMake((titleView.frame.size.width - 30) / 2,
(titleView.frame.size.height - 30) / 2, 30, 30);
[titleView addSubview:titleImage];
[titleImage release];
}
if (self.isNeedCloseBtn) {
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(mWidth - mHeaderHeight, 0,
mHeaderHeight, mHeaderHeight)];
btn.backgroundColor = [UIColor clearColor];
[btn setImage:[UIImage imageNamed:@"btn_close_alertview.png"] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(closeBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[titleView addSubview:btn];
[btn release];
}
[_backView addSubview:titleView];
self.titleBackgroundView = titleView;
[titleView release];
}
#pragma mark - 訊息區(文字或自定義視圖)
- (void)setupMessageView {
UIScrollView *msgView = [[UIScrollView alloc]
initWithFrame:CGRectMake(0, mHeaderHeight, mWidth, (mHeight - mHeaderHeight * 2))];
msgView.backgroundColor = [UIColor whiteColor];
if (self.message && [self.message length] > 0) {
CGSize messageSize = [self.message sizeWithFont:[UIFont systemFontOfSize:16.0f]
constrainedToSize:CGSizeMake(mWidth - 20, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
if (messageSize.width > 0) {
UILabel *msgLabel = [[UILabel alloc] init];
msgLabel.font = [UIFont systemFontOfSize:16.0f];
msgLabel.text = self.message;
msgLabel.numberOfLines = 0;
msgLabel.textAlignment = NSTextAlignmentCenter;
msgLabel.backgroundColor = [UIColor clearColor];
msgLabel.frame = CGRectMake(10,
((mHeight - mHeaderHeight * 2) - messageSize.height) / 2,
mWidth - 20, messageSize.height + 5);
// 內容過長時撐高彈窗並改為可滾動
if (messageSize.height > mMaxHeight) {
msgView.frame = CGRectMake(msgView.frame.origin.x, msgView.frame.origin.y,
msgView.frame.size.width, mMaxHeight + 25);
_backView.frame = CGRectMake(0, 0, mWidth,
mHeaderHeight * 2 + msgView.frame.size.height);
msgLabel.textAlignment = NSTextAlignmentLeft;
msgLabel.frame = CGRectMake(10, 10, mWidth - 20, messageSize.height);
msgView.contentSize = CGSizeMake(msgView.frame.size.width,
msgLabel.frame.size.height + 20);
} else if (messageSize.height > (mHeight - mHeaderHeight * 2) - 10) {
msgView.frame = CGRectMake(msgView.frame.origin.x, msgView.frame.origin.y,
msgView.frame.size.width, messageSize.height + 25);
_backView.frame = CGRectMake(0, 0, mWidth,
mHeaderHeight * 2 + msgView.frame.size.height);
msgLabel.frame = CGRectMake(10, 10, mWidth - 20, messageSize.height + 5);
}
[msgView addSubview:msgLabel];
[msgLabel release];
}
} else {
// 沒有文字時,改用外部塞入的子視圖
if (self.customerViewsToBeAdd && [self.customerViewsToBeAdd count] > 0) {
CGFloat startY = 0;
for (UIView *subView in self.customerViewsToBeAdd) {
CGRect rect = subView.frame;
rect.origin.y = startY;
subView.frame = rect;
[msgView addSubview:subView];
startY += rect.size.height;
}
msgView.frame = CGRectMake(0, mHeaderHeight, mWidth, startY);
}
_backView.frame = CGRectMake(0, 0, mWidth,
msgView.frame.size.height + mHeaderHeight * 2 + 20);
}
[msgView release];
[_backView addSubview:msgView];
}
#pragma mark - 按鈕區
- (void)setupButtonView {
if (_otherButtonTitles == nil && _cancelButtonTitle == nil) {
CGRect rc = _backView.frame;
rc.size.height -= mHeaderHeight;
_backView.frame = rc;
return;
}
UIView *btnView = [[UIView alloc]
initWithFrame:CGRectMake(0, _backView.frame.size.height - mHeaderHeight, mWidth, mHeaderHeight)];
if (_otherButtonTitles == nil || _cancelButtonTitle == nil) {
// 只有一個按鈕,置中
UIButton *btn = [[UIButton alloc]
initWithFrame:CGRectMake((_backView.frame.size.width - mBtnWidth) / 2, 0,
mBtnWidth, mBtnHeight)];
btn.backgroundColor = RGBA_COLOR(36, 193, 64, 1);
btn.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0f];
btn.titleLabel.textColor = [UIColor whiteColor];
if (_otherButtonTitles == nil && _cancelButtonTitle != nil) {
[btn setTitle:_cancelButtonTitle forState:UIControlStateNormal];
} else {
[btn setTitle:[_otherButtonTitles objectAtIndex:0] forState:UIControlStateNormal];
}
btn.tag = 0;
btn.layer.cornerRadius = 5;
[btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[btnView addSubview:btn];
[btn release];
} else {
// 兩個按鈕,左右並排
CGFloat startX = (_backView.frame.size.width - mBtnWidth * 2 - 20) / 2;
UIButton *otherBtn = [[UIButton alloc]
initWithFrame:CGRectMake(startX, 0, mBtnWidth, mBtnHeight)];
otherBtn.backgroundColor = RGBA_COLOR(36, 193, 64, 1);
otherBtn.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0f];
otherBtn.titleLabel.textColor = [UIColor whiteColor];
[otherBtn setTitle:[_otherButtonTitles objectAtIndex:0] forState:UIControlStateNormal];
otherBtn.layer.cornerRadius = 5;
otherBtn.tag = 0;
[otherBtn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[btnView addSubview:otherBtn];
[otherBtn release];
startX += mBtnWidth + 20;
UIButton *cancelBtn = [[UIButton alloc]
initWithFrame:CGRectMake(startX, 0, mBtnWidth, mBtnHeight)];
cancelBtn.backgroundColor = RGBA_COLOR(36, 193, 64, 1);
cancelBtn.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0f];
cancelBtn.titleLabel.textColor = [UIColor whiteColor];
[cancelBtn setTitle:_cancelButtonTitle forState:UIControlStateNormal];
cancelBtn.layer.cornerRadius = 5;
cancelBtn.tag = 1;
[cancelBtn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[btnView addSubview:cancelBtn];
[cancelBtn release];
}
[_backView addSubview:btnView];
[btnView release];
}
#pragma mark - 互動與顯示
- (void)addCustomerSubview:(UIView *)view {
[self.customerViewsToBeAdd addObject:view];
}
- (void)touchViewClickDown {
if (self.delegate && [self.delegate respondsToSelector:@selector(hideCurrentKeyBoard)]) {
[self.delegate hideCurrentKeyBoard];
}
}
- (void)buttonClicked:(id)sender {
UIButton *btn = (UIButton *)sender;
_isShow = NO;
if (btn) {
if (self.delegate &&
[self.delegate respondsToSelector:@selector(alertView:clickedButtonAtIndex:)]) {
[self.delegate alertView:self clickedButtonAtIndex:btn.tag];
}
[self removeFromSuperview];
}
}
- (void)closeBtnClicked:(id)sender {
_isShow = NO;
if (self.delegate && [self.delegate respondsToSelector:@selector(alertViewClosed:)]) {
[self.delegate alertViewClosed:self];
}
[self removeFromSuperview];
}
- (void)show {
[self layoutSubviews];
if (!_isShow) {
[[[UIApplication sharedApplication].delegate window] addSubview:self];
}
_isShow = YES;
}
- (void)dealloc {
[_backView release];
[_customerViewsToBeAdd release];
self.titleLabel = nil;
self.titleBackgroundView = nil;
self.titleIcon = nil;
[super dealloc];
}
#pragma mark - 彈出動畫
+ (void)exChangeOut:(UIView *)changeOutView dur:(CFTimeInterval)dur {
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
animation.duration = dur;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
NSMutableArray *values = [NSMutableArray array];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
animation.values = values;
animation.timingFunction = [CAMediaTimingFunction functionWithName:@"easeInEaseOut"];
[changeOutView.layer addAnimation:animation forKey:nil];
}
@end
第一,彈出動畫用了 CAKeyframeAnimation 而非 UIView 動畫,好處是能安排「放大超過 1.0 再回彈」這種帶有彈性感的關鍵幀序列,視覺上比單純的 ease-out 更有活力。
第二,這份程式碼是 MRC 寫法(大量 retain/release)。若專案使用 ARC,需要移除所有手動記憶體管理呼叫,否則無法編譯。
第三,iOS 8 之後系統已提供 UIAlertController 並在 iOS 9 正式取代 UIAlertView。若只是要顯示文字,優先使用系統元件;只有在需要嵌入自訂視圖、自訂版面時,才值得維護一份自製彈窗。此外,系統彈窗在 iPad 上會自動以 popover 呈現,自製版本若要支援 iPad,記得另外處理樣式與位置。