1. 程式人生 > >ios 自定製彈框

ios 自定製彈框

自定製類似於alertView的彈框,可以根據這個方法自定製自己想要的彈框

關鍵點是要取到controller所在window的keyWindow, [[UIApplication sharedApplication].keyWindow addSubview:self];

呼叫,在需要的地方匯入標頭檔案 #import “WindowAlert.h”

WindowAlert *alert = [WindowAlert windowAlertWith:@"popup" cancle:^{
            // 點選

        }];
        [alert show];

.h檔案

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef void(^CancleBlock)();

@interface WindowAlert : UIView

+ (instancetype)windowAlertWith:(NSString *)bgImage cancle:(CancleBlock)cancle;
- (void)show;

@property (copy,nonatomic) CancleBlock cancleBlock;
@end

.m檔案

#import "WindowAlert.h"
#import "Masonry.h" #import "MacroDefinition.h" @interface WindowAlert() @property (strong,nonatomic) UIView *bgView; @property (strong,nonatomic) UIImageView *imageView; @end @implementation WindowAlert - (instancetype)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if
(self) { [self initBgView]; } return self; } - (void)initBgView{ self.bgView = [[UIView alloc]initWithFrame:self.bounds]; [self addSubview:self.bgView]; self.bgView.backgroundColor = COLOR_HIDDEN; _imageView = [UIImageView new]; [self.bgView addSubview:_imageView]; [_imageView mas_makeConstraints:^(MASConstraintMaker *make) { make.centerX.mas_equalTo(self.bgView.bounds.origin.x).offset(0); make.centerY.mas_equalTo(self.bgView.bounds.origin.y).offset(0); make.width.mas_equalTo(280); make.height.mas_equalTo(265); }]; _imageView.userInteractionEnabled = YES; UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; [_imageView addSubview:btn]; [btn mas_makeConstraints:^(MASConstraintMaker *make) { make.centerX.mas_equalTo(_imageView.bounds.origin.x).offset(0); make.centerY.mas_equalTo(_imageView.bounds.origin.y).offset(90); make.width.mas_equalTo(95); make.height.mas_equalTo(38); }]; [btn setBackgroundImage:[UIImage imageNamed:@"popupBtn"] forState:normal]; [btn addTarget:self action:@selector(cancle:) forControlEvents:UIControlEventTouchUpInside]; } + (instancetype)windowAlertWith:(NSString *)bgImage cancle:(CancleBlock)cancle{ WindowAlert *alert = [[WindowAlert alloc]initWithFrame:CGRectMake(0, 0,WIDTH , HEIGHT)]; alert.imageView.image = [UIImage imageNamed:bgImage]; alert.cancleBlock = cancle; return alert; } - (void)show{ [[UIApplication sharedApplication].keyWindow addSubview:self]; } - (void)cancle:(UIButton *)btn{ self.cancleBlock(); [self removeFromSuperview]; } @end