天天看點

iOS自定義alertView,繼承自UIView,可以添加子視圖,标題圖檔,文字

自定義alertView,繼承自UIView,可以在消息區域添加子視圖:addCustomerSubview

标題可以有圖檔+文字構成, 隻支援兩個按鈕操作

在需要alert的控制器調用 alertView show 方法

CustomAlertView *alertView = [[CustomAlertView alloc] initWithTitle:@"提示" message:@"dylan_lwb_"  delegate:self  cancelButtonTitle:@"确定" otherButtonTitles: nil];
//  [alertView addCustomerSubview:myView];
    [alertView show];
    [alertView release];

           
//設定代理方法
 -(void)alertView:(CustomAlertView *)alertView clickedButtonAtIndex: (NSInteger)buttonIndex
{ 
}
-(void)alertViewClosed:(CustomAlertView *)alertView
{ 
}
-(void)willPresentCustomAlertView:(UIView *)alertView
{ 
} 
           

在項目裡建立一個CustomAlertView分類

#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"  //alertview present notify

    #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 ;

// - 在alertview中添加自定義控件
- (void)addCustomerSubview:(UIView *)view;

+ (void)exChangeOut:(UIView *)changeOutView dur:(CFTimeInterval)dur;

+ (CustomAlertView *)defaultAlert;

@end</mbalertviewdelegate></nsobject></uikit></foundation>



#import "CustomAlertView.h"
@interface CustomAlertView()

{
    BOOL _isShow;
}
@property (nonatomic, retain) NSString       *cancelButtonTitle;
@property (nonatomic, retain) NSMutableArray *otherButtonTitles;

@end

@implementation CustomAlertView

static const CGFloat mWidth  = ;
static const CGFloat mHeight = ;
static const CGFloat mMaxHeight    = ;
static const CGFloat mBtnHeight    = ;
static const CGFloat mBtnWidth     = ;
static const CGFloat mHeaderHeight = ;

+ (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(, , SCREEN_WIDTH, SCREEN_HEIGHT + )];
    if (self)
    {
        _isShow = NO;
    }
    return self;
}

- (id)initWithTitle:(NSString*)title message:(NSString*)message delegate:(id)del cancelButtonTitle:(NSString*)cancelBtnTitle otherButtonTitles:(NSString*)otherBtnTitles, ...
{
    self = [super initWithFrame:CGRectMake(, , SCREEN_WIDTH, SCREEN_HEIGHT + )];
    if (self)
    {
        self.delegate = del;
        self.cancelButtonTitle = cancelBtnTitle;
        self.isNeedCloseBtn = NO;

        if (!_otherButtonTitles)
        {
            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];
            }
        }
        self.title = title;
        self.message = message;

    }
    return self;
}

-(void)initTitle:(NSString*)title message:(NSString*)message delegate:(id)del cancelButtonTitle:(NSString*)cancelBtnTitle otherButtonTitles:(NSString*)otherBtnTitles, ...
{
    if (self)
    {
        self.delegate = del;
        self.cancelButtonTitle = cancelBtnTitle;
        self.isNeedCloseBtn = NO;

        if (!_otherButtonTitles)
        {
            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];
            }
        }
        self.title = title;
        self.message = message;
    }
}

- (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:];
    [self addSubview:bgView];
    [bgView release];

    if (!_backView)
    {
        _backView = [[UIView alloc] initWithFrame:CGRectMake(, , mWidth, mHeight)];
        _backView.opaque = NO;
        _backView.backgroundColor     = [UIColor whiteColor];
        _backView.layer.shadowOffset  = CGSizeMake(, );
        _backView.layer.shadowRadius  = ;
        _backView.layer.shadowColor   = [UIColor grayColor].CGColor;
        _backView.layer.shadowOpacity = ;
        [_backView.layer setMasksToBounds:NO];
    }

    // - 設定頭部顯示區域
    // - 設定标題背景
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(, , mWidth, mHeaderHeight)];
    titleView.backgroundColor = RGBA_COLOR(, , , );

    CGSize titleSize = CGSizeZero;
    if (self.title && [self.title length] > )
    {
        titleSize = [self.title sizeWithFont:[UIFont fontWithName:@"Helvetica-Bold" size:f]];
    }
    if (titleSize.width > )
    {
        // - 标題圖檔
        CGFloat startX = (titleView.frame.size.width -  - titleSize.width) / ;
        UIImageView *titleImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xxxxx.png"]];
        titleImage.frame = CGRectMake(startX, (titleView.frame.size.height - ) / , , );
        self.titleIcon = titleImage;

        [titleView addSubview:titleImage];
        [titleImage release];
        startX += ;

        // - 标題
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(startX, (titleView.frame.size.height - ) / , titleSize.width, )];

        //- 标題太長的話需要處理
        if (titleLabel.frame.size.width > )
        {
            titleLabel.frame = CGRectMake(, (titleView.frame.size.height - ) / , mWidth - , );

            titleImage.frame = CGRectMake(, (titleView.frame.size.height - ) / , , );

        }

        titleLabel.text = self.title;
        titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:f];
        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 - ) / , (titleView.frame.size.height - ) / , , );
        [titleView addSubview:titleImage];
        [titleImage release];
    }

    if (self.isNeedCloseBtn)
    {
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(mWidth-mHeaderHeight, , 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];

    // - 設定消息顯示區域
    UIScrollView *msgView = [[UIScrollView alloc] initWithFrame:CGRectMake(, mHeaderHeight, mWidth, (mHeight-mHeaderHeight * ))];

    // - 設定背景顔色
    msgView.backgroundColor = [UIColor whiteColor];

    // - 内容
    CGSize messageSize = CGSizeZero;
    if (self.message && [self.message length]>)
    {
        messageSize = [self.message sizeWithFont:[UIFont systemFontOfSize:f] constrainedToSize:CGSizeMake(mWidth-, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];

        if (messageSize.width > )
        {
            UILabel *msgLabel = [[UILabel alloc] init];
            msgLabel.font = [UIFont systemFontOfSize:f];
            msgLabel.text = self.message;
            msgLabel.numberOfLines   = ;
            msgLabel.textAlignment   = NSTextAlignmentCenter;
            msgLabel.backgroundColor = [UIColor clearColor];
            msgLabel.frame = CGRectMake(, ((mHeight - mHeaderHeight * ) - messageSize.height) / , mWidth-, messageSize.height + );
            if(messageSize.height > mMaxHeight)
            {
                msgView.frame = CGRectMake(msgView.frame.origin.x, msgView.frame.origin.y, msgView.frame.size.width, mMaxHeight + );
                _backView.frame = CGRectMake(, , mWidth, mHeaderHeight *  + msgView.frame.size.height);
                msgLabel.textAlignment = NSTextAlignmentLeft;
                msgLabel.frame = CGRectMake(, , mWidth - , messageSize.height);
                msgView.contentSize = CGSizeMake(msgView.frame.size.width, msgLabel.frame.size.height + );
            }
            else if (messageSize.height > (mHeight-mHeaderHeight * ) - )
            {
                msgView.frame = CGRectMake(msgView.frame.origin.x, msgView.frame.origin.y, msgView.frame.size.width, messageSize.height + );
                _backView.frame = CGRectMake(, , mWidth, mHeaderHeight *  + msgView.frame.size.height);
                msgLabel.frame = CGRectMake(, , mWidth - , messageSize.height + );
            }
            [msgView addSubview:msgLabel];
            [msgLabel release];
            [_backView addSubview:msgView];
        }
    }else{
        if (self.customerViewsToBeAdd && [self.customerViewsToBeAdd count] > )
        {
            CGFloat startY = ;
            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(, mHeaderHeight, mWidth, startY);
        }
        [_backView addSubview:msgView];
        _backView.frame = CGRectMake(, , mWidth, msgView.frame.size.height + mHeaderHeight *  +);
    }
    [msgView release];

    // - 設定按鈕顯示區域
    if (_otherButtonTitles != nil || _cancelButtonTitle != nil)
    {
        UIView *btnView = [[UIView alloc] initWithFrame:CGRectMake(, _backView.frame.size.height-mHeaderHeight, mWidth, mHeaderHeight)];

        // - 如果隻顯示一個按鈕,需要計算按鈕的顯示大小
        if (_otherButtonTitles == nil || _cancelButtonTitle == nil)
        {
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake((_backView.frame.size.width-mBtnWidth) /  , , mBtnWidth, mBtnHeight)];
            btn.backgroundColor = RGBA_COLOR(, , , );
            btn.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:f];
            btn.titleLabel.textColor = [UIColor whiteColor];
            [btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
            if (_otherButtonTitles == nil && _cancelButtonTitle != nil)
            {
                [btn setTitle:_cancelButtonTitle forState:UIControlStateNormal];
            } else
            {
                [btn setTitle:[_otherButtonTitles objectAtIndex:] forState:UIControlStateNormal];
            }
            btn.tag = ;
            btn.layer.cornerRadius = ;
            [btnView addSubview:btn];
            [btn release];
        }
        else if(_otherButtonTitles && [_otherButtonTitles count] == )
        {
            // - 顯示兩個按鈕
            // - 設定确定按鈕的相關屬性
            CGFloat startX = (_backView.frame.size.width-mBtnWidth*-)/;
            UIButton *otherBtn = [[UIButton alloc]initWithFrame:CGRectMake(startX, , mBtnWidth, mBtnHeight)];
            otherBtn.backgroundColor = RGBA_COLOR(, , , );
            otherBtn.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:f];
            otherBtn.titleLabel.textColor = [UIColor whiteColor];
            [otherBtn setTitle:[_otherButtonTitles objectAtIndex:] forState:UIControlStateNormal];
            otherBtn.layer.cornerRadius = ;
            [otherBtn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
            otherBtn.tag = ;
            [btnView addSubview:otherBtn];
            [otherBtn release];
            startX += mBtnWidth+;

            // - 設定取消按鈕的相關屬性
            UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(startX, , mBtnWidth, mBtnHeight)];
            cancelBtn.backgroundColor = RGBA_COLOR(, , , );
            cancelBtn.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:f];
            cancelBtn.titleLabel.textColor = [UIColor whiteColor];
            [cancelBtn setTitle:_cancelButtonTitle forState:UIControlStateNormal];
            cancelBtn.layer.cornerRadius = ;
            [cancelBtn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
            cancelBtn.tag = ;
            [btnView addSubview:cancelBtn];
            [cancelBtn release];
        }
        [_backView addSubview: btnView];
        [btnView release];
    }
    else
    {
        CGRect rc = _backView.frame;
        rc.size.height -= mHeaderHeight;
        _backView.frame = rc;
    }

    UIControl *touchView = [[UIControl alloc] initWithFrame:self.frame];
    [touchView addTarget:self action:@selector(touchViewClickDown) forControlEvents:UIControlEventTouchDown];
    touchView.frame = self.frame;
    [self addSubview:touchView];
    [touchView release];
    _backView.center = self.center;


    [self addSubview:_backView];

    if (!_isShow)
        [CustomAlertView exChangeOut:_backView dur:];
    if (self.delegate)
    {
        if ([self.delegate respondsToSelector:@selector(willPresentCustomAlertView:)])
        {
            [self.delegate willPresentCustomAlertView:self];
        }

        [[NSNotificationCenter defaultCenter] postNotificationName:kBCAlertViewPresentNotify object:nil userInfo:nil];
    }
}
- (void)touchViewClickDown
{
    if (self.delegate)
    {
        if ([self.delegate respondsToSelector:@selector(hideCurrentKeyBoard)])
        {
            [self.delegate hideCurrentKeyBoard];
        }
    }
}

// - 在消息區域設定自定義控件
- (void)addCustomerSubview:(UIView *)view
{
    [self.customerViewsToBeAdd addObject:view];
}

- (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];  
}

// - alertview彈出動畫
+ (void)exChangeOut:(UIView *)changeOutView dur:(CFTimeInterval)dur
{
    CAKeyframeAnimation * animation;
    animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];

    animation.duration = dur;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;

    NSMutableArray *values = [NSMutableArray array];

    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(, , )]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(, , )]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(, , )]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(, , )]];

    animation.values = values;
    animation.timingFunction = [CAMediaTimingFunction functionWithName: @"easeInEaseOut"];

    [changeOutView.layer addAnimation:animation forKey:nil];
}

@end