使用delegate自定义UIAlertView

来源:互联网 发布:水族馆 知乎 编辑:程序博客网 时间:2024/05/20 19:46

IOS自带的UIAlertView很多时候并不能满足我们项目的UI需求,这时候就需要自定义UIAlertView。

下面是用delegate(不懂IOS delegate的同学可以百度下)自定义的一个UIAlertView,继承自UIView,取名为CustomeAlert;

首先需要添加CustomeAlert的UI,我这里是用一个xib文件(如下图),这里有两部分,一是设置一定透明度的背景,另外就是弹出框的内容,我设置的偏宽就是为了后面弹出框的动画做准备。


接下来在CustomeAlert.h里面添加代理,这里定义了一个代理方法,就是alertView的点击的button,0取消1确定

@protocol CustomeAlertDelegate <NSObject>@optional- (void)alertButtonClicked:(NSInteger) buttonIndex;@end
并且添加delegate这个属性
@property (nonatomic,assign) id<CustomeAlertDelegate> delegate;

然后在.m初始化CustomeAlert,这里需要注意我是xib加载的,所以是作为其子类,如果直接self = [[[NSBundlemainBundle]loadNibNamed:@"customeAlert"owner:selfoptions:nil]lastObject]则设置delegate和点击事件都会crash,如果用代码不是直接拖拽控件来生成上面的UI则可以直接等于,不需要作为其子类添加(个人见解,没有验证,有兴趣的同学可以去测试验证下)。

- (instancetype)initWithFrame:(CGRect)frame {    self = [super initWithFrame:frame];    if(self){        UIView *view = [[[NSBundle mainBundle]loadNibNamed:@"customeAlert" owner:self options:nil]lastObject];        <u><em>[self addSubview:view];</em></u>    }    self.backgroundColor = [UIColor clearColor];    //设置弹出框的样式和动画    [self alertViewShow];    return self;}
//设置alertView的样式和动画- (void)alertViewShow{    //设置圆角    self.alertContentView.layer.masksToBounds = YES;    self.alertContentView.layer.cornerRadius = 8.0;    //动画    [UIView animateWithDuration:0.3 animations:^{        self.alertContentView.transform = CGAffineTransformScale(self.alertContentView.transform, 0.9, 0.9);    }];}
接下来是button事件,点击button同时要移除此类 用removeFromSuperview。
//按下取消按钮- (IBAction)pressedCancelButton:(UIButton *)sender {    if([_delegate respondsToSelector:@selector(alertButtonClicked:)]){        [_delegate alertButtonClicked:0];    }    [self removeFromSuperview];}//按下了确定键- (IBAction)pressedEnsureButton:(UIButton *)sender {    if([_delegate respondsToSelector:@selector(alertButtonClicked:)]){        [_delegate alertButtonClicked:1];    }    [self removeFromSuperview];}
这样就差不多做好了CustomeAlert了,然后就是ViewController应用自定义的alertView了。

在引入头文件和声明代理@interface ViewController () <CustomeAlertDelegate>后就可以了

//弹出自定义的alertView- (IBAction)customeAlertView:(UIButton *)sender {    customeAlert *alert = [[customeAlert alloc] initWithFrame:self.view.frame];    alert.delegate = self;    [self.view addSubview:alert];}

#pragma mark- 代理- (void)alertButtonClicked:(NSInteger)buttonIndex{    if(buttonIndex == 0){        NSLog(@"您按下了取消键");    }    if(buttonIndex == 1){        NSLog(@"您按下了确定键");    }}
截图效果








0 0
原创粉丝点击