1、首先继承UIView拖出一个XIB文件的类,如图定制一个简单的弹窗
2、在.h文件中相应的名称
typedef void(^ButtonBlock)(void);
@interface SimpleAlertView : UIView
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (nonatomic,copy) ButtonBlock cancelButtonBlock;
@property (nonatomic,copy) ButtonBlock confirmButtonBlock;
+ (instancetype)getSimpleView;
- (void)show;
- (void)dismiss;
3、在.m中实现相应 的方法
+ (instancetype)getSimpleView{
NSArray *objs = [[NSBundle mainBundle] loadNibNamed:@"SimpleAlertView" owner:nil options:nil];
return [objs lastObject];
}
- (void)awakeFromNib{
self.frame = [[UIScreen mainScreen] bounds];
self.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.0];
self.alertView.alpha = 0.0;
self.alertView.layer.borderWidth = 0.5f;
self.alertView.layer.borderColor = [UIColor grayColor].CGColor;
self.cancelBtn.backgroundColor = [UIColor greenColor];
self.confirmBtn.backgroundColor = [UIColor greenColor];
self.cancelBtn.layer.borderWidth = 0.5f;
self.cancelBtn.layer.borderColor = [UIColor grayColor].CGColor;
self.confirmBtn.layer.borderWidth = 0.5f;
self.confirmBtn.layer.borderColor = [UIColor grayColor].CGColor;
self.titleLabel.font = [UIFont boldSystemFontOfSize:17.0f];
}
- (void)show{
[[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:self];
_alertView.transform = CGAffineTransformScale(_alertView.transform,1.3,1.6);
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
_alertView.transform = CGAffineTransformIdentity;
self.alertView.alpha = 1.0;
} completion:nil];
}
- (void)dismiss{
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
self.alpha = 0.0;
self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0];
_alertView.transform = CGAffineTransformScale(_alertView.transform,0.9,0.9);
} completion:^(BOOL finished) {
if (finished) {
[self removeFromSuperview];
}
}];
}
- (IBAction)cancelBtn:(id)sender {
if (self.cancelButtonBlock) {
self.cancelButtonBlock();
}
[self dismiss];
}
- (IBAction)confirmBtn:(id)sender {
if (self.confirmButtonBlock) {
self.confirmButtonBlock();
}
[self dismiss];
}
@property (weak, nonatomic) IBOutlet UIView *alertView;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;
4、然后在需要弹窗的地方直接加载定制好的XIB文件即可
/**
* 使用XIB快速构建alert,
*/
- (IBAction)simpleAlert:(id)sender {
SimpleAlertView *alertView = [SimpleAlertView getSimpleView];
alertView.titleLabel.text = @"SimpleAlertView";
alertView.contentLabel.text = @"simpleAlertView!!!!";
alertView.cancelButtonBlock = ^{
NSLog(@" 1111111");
};
alertView.confirmButtonBlock = ^{
NSLog(@" 2222222");
};
[alertView show];
}
最终效果