最近刚刚接触iOS的的开发,总结一下自己的心得体会.我们做iOS开发的时候,弹出对话框基本上都是使用系统提供的UIAlertView. 但是有时候系统提供的未必能够满足我们的需求,这个时候就需要我们自定义一个自己的UIAlertView,下面我们就来看看怎么样创建.
首先,我们创建一个继承于UIView的类CustomAlertView,接口定义文件如下:
#import <UIKit/UIKit.h>
//设置一个简单回调函数
typedef void (^CustomAlertViewBlock)();
@interface CustomAlertView : UIView
@property (nonatomic, copy) CustomAlertViewBlock finishBlock;
//设置显示方法
-(void)show;
//设置隐藏方法
-(void)hide;
@end
然后,实现文件(CustomAlertView.m)如下:
#import "CustomAlertView.h"
@interface CustomAlertView()
@property (weak, nonatomic) IBOutlet UIView *view;
@end
@implementation CustomAlertView
-(instancetype)init{
self = [super init];
if (self) {
self = [[NSBundle mainBundle] loadNibNamed:@"CustomAlertView" owner:self options:nil].lastObject;
}
//设置弹出框的圆角
_view.layer.borderWidth = 0.5;
_view.layer.cornerRadius = 5;
_view.layer.masksToBounds = YES;
return self;
}
//实现显示方法
-(void)show{
[[UIApplication sharedApplication].keyWindow addSubview:self];
}
//隐藏窗口
-(void)hide{
[self removeFromSuperview];
}
- (IBAction)doCancelBtn:(UIButton *)sender {
[self hide];
}
- (IBAction)doOKBtn:(UIButton *)sender {
//回调函数
if (_finishBlock) {
_finishBlock();
}
//可以在这里处理请求信息
[self hide];
}
@end
最后是调用方法:
- (IBAction)doAlertViewShow:(UIButton *)sender {
CustomAlertView *custome = [[CustomAlertView alloc]init];
[custome show];
//回调函数,关闭CustomAlertView后的后续操作,比如重新向服务器请求数据,刷新当前界面
custome.finishBlock = ^{
[_showBtn setBackgroundColor:[UIColor redColor]];
};
这样一个简单的自定义对话框就完成了.