使用:
[MSAlertSheetView alertSheetViewWithButtons:@[@"男",@"女",@"取消"] CallBack:^(NSInteger index) {
if (index == 2) {
return ;
}
[self modifySexWithIndex:index];
}];
源码
#import "MSAlertSheetView.h"
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kActionH 40
#define kActionW kScreenW - 40
#define kPadding 20
@interface MSAlertSheetView ()
@property(assign,nonatomic) CGFloat alertVH;
@property(strong,nonatomic) UIView *alertV;
@end
@implementation MSAlertSheetView
static MSAlertSheetView *alerView = nil;
+ (instancetype)defaultSingle{
if(alerView == nil){
alerView = [[MSAlertSheetView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
}
[alerView makeUI];
return alerView;
}
- (void)makeUI{
UIWindow *window = [UIApplication sharedApplication].keyWindow;
alerView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
alerView.frame = window.frame;
[window addSubview:alerView];
[UIView animateWithDuration:0.5 animations:^{
alerView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
}];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:alerView action:@selector(didClickMaskView)];
[alerView addGestureRecognizer:tap];
}
+(void)alerViewWithButtons:(NSArray<NSString *> *)btns CallBack:(CallBack)callBack{
alerView = [MSAlertSheetView defaultSingle];
NSInteger count = btns.count;
alerView.alertVH = kActionH * (count + 2) + kPadding *(count - 1);
UIView *alertV = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenH , kScreenW, alerView.alertVH)];
[UIView animateWithDuration:0.5 animations:^{
alertV.frame = CGRectMake(0, kScreenH- alerView.alertVH, kScreenW, alerView.alertVH);
}];
alertV.backgroundColor = [UIColor redColor];
alerView.alertV = alertV;
[alerView addSubview:alertV];
UIButton *lastBtn = nil;
int i = 0;
for (NSString *actionStr in btns) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:actionStr forState:UIControlStateNormal];
btn.tag = i;
if (lastBtn == nil) {
btn.frame = CGRectMake(kPadding, kActionH, kActionW, kActionH);
}else{
btn.frame = CGRectMake(kPadding, kActionH + i *(kPadding + kActionH), kActionW, kActionH);
}
btn.backgroundColor = [UIColor lightGrayColor];
lastBtn = btn;
alerView.callBack = callBack;
[btn addTarget:alerView action:@selector(didClickBtn:) forControlEvents:UIControlEventTouchUpInside];
[alertV addSubview:btn];
i++;
}
}
- (void)didClickBtn:(UIButton *)btn{
alerView.callBack(btn.tag);
[alerView dismiss];
}
- (void)didClickMaskView{
[alerView dismiss];
}
- (void)dismiss{
[UIView animateWithDuration:0.5 animations:^{
alerView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
alerView.alertV.frame = CGRectMake(0, kScreenH , kScreenW, alerView.alertVH);
} completion:^(BOOL finished) {
[alerView removeFromSuperview];
alerView = nil;
}];
}
@end