1. 程式人生 > >iOS 兩款你可能會用到的彈出框

iOS 兩款你可能會用到的彈出框

前言

好久沒寫部落格了……最近拿到了一版原型圖,各種彈框,簡直快把老爺給彈死了……因為實現功能是其次的,最主要還得把這些東西給封裝一下,方便同事的呼叫。於是乎,我就開始了爬坑的過程。經過兩天的耕耘,出了兩款風格迥異的彈框,這裡給大家分享一下。。。同時也祭奠一下,我老去的容顏……

效果圖

底部PickerView彈框(這個東西還是蠻常見的)

view.gif

中間TextView彈框(這個東西真不常見,Alert支援的是單行輸入,也就是textField)

vie.gif
底部PickerView彈框(LHEditPickerView)

首先生成了一個LHEditPickView這個就是大家看到的那個彈出框的實體view
程式碼如下:
LHEditPickView.h

#import <UIKit/UIKit.h>

@interface LHEditPickView : UIView

/**
 *  背景圖(半透明全屏)
 */
@property (nonatomic,weak)UIView *blackBgView;

/**
 *  下部彈出框的ToolBar
 */
@property (nonatomic,weak)UIToolbar *toolBarView;

/**
 *  彈出框主題背景
 */
@property (nonatomic,weak)UIView *mainBgView;

/**
 *  部門選擇PickView
 */
@property
(nonatomic,weak)UIPickerView *pickerView; /** * 取消按鈕 */ @property (nonatomic,weak)UIButton *cancelBtn; /** * 確定按鈕 */ @property (nonatomic,weak)UIButton *sureBtn; @property (nonatomic,strong)NSArray *data; @property (nonatomic,copy) void (^refreshUserInterface)(NSString *); @property (nonatomic
,copy) void (^dropEditPickerView)(); @end'

LHEditPickView.m

#import "LHEditPickView.h"

@interface LHEditPickView()<UIPickerViewDelegate,UIPickerViewDataSource>{
//按鈕的寬度
CGFloat _btnWidth;
NSString *_result;
}

@end

@implementation LHEditPickView

-(instancetype)initWithFrame:(CGRect)frame{
self=[super initWithFrame:frame];
if(self){
    //主背景圖
    UIView *mainBgView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    self.mainBgView=mainBgView;
    mainBgView.backgroundColor=[UIColor whiteColor];
    [self addSubview:mainBgView];
    
    //ToolBar
    UIToolbar *toolView=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height/6)];
    [toolView setBackgroundImage:[UIImage imageNamed:@"daohangtiao"] forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    self.toolBarView=toolView;
    toolView.backgroundColor=[UIColor blueColor];
    [mainBgView addSubview:toolView];
    
    //取消,確定按鈕
    _btnWidth=100.0;
    UIButton *cancelbtn=[UIButton buttonWithType:UIButtonTypeCustom];
    cancelbtn.frame=CGRectMake(0, 0, _btnWidth, CGRectGetHeight(toolView.frame));
    [cancelbtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelbtn addTarget:self action:@selector(onclickCancel:) forControlEvents:UIControlEventTouchUpInside];
    self.cancelBtn=cancelbtn;
    [toolView addSubview:cancelbtn];
    
    _btnWidth=100.0;
    UIButton *sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame=CGRectMake(frame.size.width-_btnWidth, 0, _btnWidth, CGRectGetHeight(toolView.frame));
    [sureBtn setTitle:@"確定" forState:UIControlStateNormal];
    self.sureBtn=sureBtn;
    [self.sureBtn addTarget:self action:@selector(onclickSure:) forControlEvents:UIControlEventTouchUpInside];
    [toolView addSubview:sureBtn];
    
    
    
    //UIPickerView
    UIPickerView *picker=[[UIPickerView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(toolView.frame), frame.size.width, (frame.size.height/6)*5)];
    self.pickerView=picker;
    picker.showsSelectionIndicator=YES;
    picker.delegate=self;
    picker.dataSource=self;
    [mainBgView addSubview:picker];
    
}
return self;
}

//設定data並且設設定_result的初始值
-(void)setData:(NSArray *)data{
if(_data!=data){
    _data=data;
    _result=data[0];
}
//重新整理所有元素
[self.pickerView reloadAllComponents];
}

#pragma mark -ButtonClick

-(void)onclickCancel:(id)sender{
if(self.dropEditPickerView){
    self.dropEditPickerView();
}
}

//確定按鈕,block傳值
-(void)onclickSure:(id)sender{
if(self.refreshUserInterface){
    self.refreshUserInterface(_result);
}
if(self.dropEditPickerView){
    self.dropEditPickerView();
}
}

#pragma mark -PickerViewDelegate
//有多少行
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return self.data.count;
}
//有多少列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}

//設定每一行的內容
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return self.data[row];
}

//設定選中結果
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
_result=self.data[row];
}

@end

由於本人習慣於程式碼佈局,所以很low……呵呵噠
現在主體顯示的部分已經有了,現在就該操心怎麼將它顯示出來了,於是我又建立了一個類——LHBottomPickerView(顯示LHEditPickView)廢話不多說,上程式碼:
LHBottomPickerView.h

#import <UIKit/UIKit.h>

#import "LHEditPickView.h"
@interface LHBottomPickerView : UIView
@property (nonatomic,weak)UIView *grayBgView;
@property (nonatomic,weak)LHEditPickView *editView;
@property (nonatomic,weak)UIViewController *controller;
@property (nonatomic,copy)void (^bottomResultPresent)(NSString *);
@property (nonatomic,strong)UITapGestureRecognizer *recognizer;

+(instancetype)showWithController:(UIViewController *)controller andData:(NSArray *)data;
-(instancetype)initWithController:(UIViewController *)controller;

+(void)showEditPickerViewWithController:(UIViewController *)controller andData:(NSArray *)data andBlock:(void (^)(NSString *temp))bottomResultPresent;

@end

LHBottomPickerView.m

#import "LHBottomPickerView.h"
#import "AppDelegate.h"

@interface LHBottomPickerView()<UIGestureRecognizerDelegate>

@end

@implementation LHBottomPickerView

-(instancetype)initWithController:(UIViewController *)controller{
self=[super init];
if(self){
    //黑色半透明背景
    AppDelegate *app=(AppDelegate *)[UIApplication sharedApplication].delegate;
    UIView *grayBgView=[[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    grayBgView.backgroundColor=[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [app.window.rootViewController.view addSubview:grayBgView];
    grayBgView.hidden=YES;
    self.grayBgView=grayBgView;
    
    //為grayBgView新增點選手勢
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] init];
    tapGestureRecognizer.numberOfTapsRequired = 1; // 設定單擊幾次才觸發方法
    [self.grayBgView setUserInteractionEnabled:YES];
    tapGestureRecognizer.delegate=self;
    [tapGestureRecognizer addTarget:self action:@selector(popAndPushPickerView)]; // 新增點選手勢的方法
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.grayBgView addGestureRecognizer:tapGestureRecognizer];
    self.recognizer=tapGestureRecognizer;
    
    
    //LHEditPickerView
    LHEditPickView *editView=[[LHEditPickView alloc]initWithFrame:CGRectMake(0, controller.view.bounds.size.height, controller.view.bounds.size.width, controller.view.bounds.size.height/5*2)];
    self.editView=editView;
    self.editView.refreshUserInterface=^(NSString * result){
        if(self.bottomResultPresent){
            self.bottomResultPresent(result);
        }
    };
    self.editView.dropEditPickerView=^(){
        [self popAndPushPickerView];
    };
    [self.grayBgView addSubview:editView];
    
}
return self;
}

+(instancetype)showWithController:(UIViewController *)controller andData:(NSArray *)data{
LHBottomPickerView *bottom=[[self alloc]initWithController:controller];
bottom.controller=controller;
bottom.editView.data=data;
[controller.view addSubview:bottom];
[bottom popAndPushPickerView];
return  bottom;
}

-(void)popAndPushPickerView{
if(self.grayBgView.hidden){
    [UIView animateWithDuration:0.5 animations:^{
        self.grayBgView.hidden=NO;
        self.editView.frame=CGRectMake(0, self.controller.view.bounds.size.height/5*3, self.controller.view.bounds.size.width, self.controller.view.bounds.size.height/5*2);
    }];
    [self.grayBgView setUserInteractionEnabled:YES];
}else{
    [UIView animateWithDuration:0.5 animations:^{
        self.editView.frame=CGRectMake(0, self.controller.view.bounds.size.height, self.controller.view.bounds.size.width, self.controller.view.bounds.size.height/5*2);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 animations:^{
            self.grayBgView.hidden=YES;
        }];
    }];
    
}

}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
if ( [touch.view isKindOfClass:[UIButton class]])
{
    return NO;
}
//由於LHEdiPickView中的toolView也受到了手勢的影響,所以在這裡將這這個ToolView遮蔽掉
if([touch.view isKindOfClass:[UIToolbar class]]){
    return NO;
}

return YES;
}

+(void)showEditPickerViewWithController:(UIViewController *)controller andData:(NSArray *)data andBlock:(void (^)(NSString *temp))bottomResultPresent{
LHBottomPickerView *bottom=[LHBottomPickerView showWithController:controller andData:data];
bottom.bottomResultPresent=bottomResultPresent;
}

@end

下面就是最神奇的地方,呼叫竟然會如此簡單,還是上程式碼:
ViewController.h

#import "ViewController.h"
#import "LHBottomPickerView.h"
@interface ViewController ()
@property (nonatomic,weak)UIView *grayBgView;
@property (nonatomic,weak)LHEditPickView *editView;
@property (nonatomic,weak)UILabel *label;
@property (nonatomic,weak)UIButton *button;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(0, 0, 100, 100);
button.backgroundColor=[UIColor redColor];
[self.view addSubview:button];
self.button=button;
[button addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];

}

-(void)clickBtn{
//**看到沒,就是這麼簡單**
[LHBottomPickerView showEditPickerViewWithController:self andData:@[@"早晨",@"中午",@"下午"] andBlock:^(NSString *temp) {
    [self.button setTitle:temp forState:UIControlStateNormal];
}];

}

@end

總結一下知識點:

  • block使用:block屬性、block引數、block傳遞、block回撥
  • 手勢衝突
彈出TextView彈框(LHPopTextView)

這個彈框,當時寫的時候就想去用AlertController或者AlertView,但是發現alertView和AlertController自帶的是一個TextField,並且還是單行的,顯然滿足不了我的需求,真心不想自己寫這一部分東西,但是最後,還是重寫吧,因為沒有,所以得造。

  • 這個與上一個效果略有不同,就是那個灰色的遮蓋,第一個是用了UIView然後添加了手勢,但是新增手勢以後,會出現手勢衝突,所以這個我把背景遮蓋給換成了一個UIButton,這樣子省了不少的功夫。程式碼如下:

LHTopTextView.h(彈出框的檢視)

#import <UIKit/UIKit.h>

@interface LHTopTextView : UIView

@property (nonatomic,weak)UITextView *textView;
@property (nonatomic,weak)UIButton *submitBtn;
@property (nonatomic,weak)UIButton *cancelBtn;

@property (nonatomic,weak)UILabel *titleLabel;

@property (nonatomic,copy) void(^submitBlock)(NSString * text);
@property (nonatomic,copy) void(^closeBlock)();

@end

LHTopTextView.m

#import "LHTopTextView.h"

@interface LHTopTextView()<UITextViewDelegate>{
CGFloat _space;
NSString *_text;
CGFloat _margin;
}
@end

@implementation LHTopTextView

-(instancetype)initWithFrame:(CGRect)frame{
self=[super initWithFrame:frame];
if(self){
    //設定兩個控制元件之間的間距
    _space=10.0;
    
    //設定與邊框的間距
    _margin=15.0;
    
    //設定圓角
    self.layer.cornerRadius=5;
    [self.layer setMasksToBounds:YES];
    
    //設定背景色
    self.backgroundColor=[UIColor whiteColor];
    
    //駁回申訴
    UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake((frame.size.width-2*_margin)/3+_margin, _margin,(frame.size.width-2*_margin)/3, (frame.size.height-_margin*2-_space)/7)];
    self.titleLabel=titleLabel;
    [self addSubview:titleLabel];
    [titleLabel setFont:[UIFont systemFontOfSize:20]];
    titleLabel.textAlignment=NSTextAlignmentCenter;
    [titleLabel setText:@"駁回申訴"];
    //輸入框
    UITextView *textView=[[UITextView alloc]initWithFrame:CGRectMake(_margin, CGRectGetMaxY(titleLabel.frame)+_space, frame.size.width-2*_margin, CGRectGetHeight(titleLabel.frame)*4)];
    textView.backgroundColor=[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.739140070921986];
    self.textView=textView;
    textView.font=[UIFont systemFontOfSize:15];
    NSString *str=@"請您輸入您對處理結果的評價,最多128個字";
    textView.textColor=[UIColor whiteColor];
    textView.text=str;
    textView.returnKeyType=UIReturnKeyDone;
    textView.delegate=self;
    [self addSubview:textView];
    
    //seperateLine
    UIView *lineView=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(textView.frame)+_margin, frame.size.width, 1)];
    lineView.backgroundColor=[UIColor grayColor];
    [self addSubview:lineView];
    
    //取消按鈕
    UIButton *cancelBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame=CGRectMake(0, CGRectGetMaxY(lineView.frame), frame.size.width/2, CGRectGetHeight(titleLabel.frame)*2);
    [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cancelBtn setTitle:@"關閉" forState:UIControlStateNormal];
    self.cancelBtn=cancelBtn;
    [cancelBtn addTarget:self action:@selector(clickCancel:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:cancelBtn];
    
    //按鈕分隔線
    UIView *seperateLine=[[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(cancelBtn.frame), CGRectGetMinY(cancelBtn.frame), 1, CGRectGetHeight(cancelBtn.frame))];
    seperateLine.backgroundColor=[UIColor grayColor];
    [self addSubview:seperateLine];

    //確定按鈕
    UIButton *sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame=CGRectMake(CGRectGetMaxX(seperateLine.frame), CGRectGetMinY(cancelBtn.frame), CGRectGetWidth(cancelBtn.frame), CGRectGetHeight(cancelBtn.frame));
    self.submitBtn=sureBtn;
    [sureBtn setTitle:@"提交" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(clickSubmit:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:sureBtn];
    
}
return self;
}

-(void)textViewDidBeginEditing:(UITextView *)textView{
textView.textColor=[UIColor blackColor];
textView.text=nil;
}
/**
 * 通過代理方法去設定不能超過128個字,但是可編輯
 */
#pragma mark -UITextViewDelegate
-(void)textViewDidChange:(UITextView *)textView{
if(textView.text.length>=128){
   textView.text=[textView.text substringToIndex:127];
}
}

#pragma mark -return鍵彈回鍵盤
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{

if ([text isEqualToString:@"\n"]) {
    
    [textView resignFirstResponder];
    
    return NO;
    
}
return YES;    

}

#pragma mark -處理確定點選事件

-(void)clickSubmit:(id)sender{
if(self.textView.editable){
    [self.textView resignFirstResponder];
}
if(self.textView.text.length>0){
    if([self.textView.textColor isEqual:[UIColor redColor]]||[self.textView.textColor isEqual:[UIColor whiteColor]]){
        [self.textView becomeFirstResponder];
    }else{
        if(self.submitBlock){
            self.submitBlock(self.textView.text);
        }
    }
}else{
    self.textView.textColor=[UIColor redColor];
    self.textView.text=@"您輸入的內容不能為空,請您輸入內容";
}
}

#pragma mark -處理取消點選事件

-(void)clickCancel:(id)sender{
if(self.closeBlock){
    self.closeBlock();
}
}

@end

LHEditTextView.h(顯示彈出框和遮蓋的檢視)

#import <UIKit/UIKit.h>

@interface LHEditTextView : UIView

@property (nonatomic,weak)UIButton *grayBgView;
@property (nonatomic,copy)void (^requestDataBlock)(NSString *text);

+(instancetype)showWithController:(UIViewController *)controller;
+(void)showWithController:(UIViewController *)controller andRequestDataBlock:(void(^)(NSString *))requestDataBlock;
@end

LHEditTextView.m

#import "LHEditTextView.h"
#import "AppDelegate.h"
#import "LHTopTextView.h"

@interface LHEditTextView()<UIGestureRecognizerDelegate>

@property (nonatomic,weak)LHTopTextView *topTextView;
@property (nonatomic,weak)UIViewController *controller;
@end

@implementation LHEditTextView

-(instancetype)initWithController:(UIViewController *)controller{
self=[super init];
if(self){
    //黑色半透明背景
    AppDelegate *app=(AppDelegate *)[UIApplication sharedApplication].delegate;
    UIButton *grayBgView=[UIButton buttonWithType:UIButtonTypeCustom];
    grayBgView.frame=[UIScreen mainScreen].bounds;
    grayBgView.backgroundColor=[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    [app.window.rootViewController.view addSubview:grayBgView];
    grayBgView.hidden=YES;
    self.grayBgView=grayBgView;
    
    
    [grayBgView addTarget:self action:@selector(popAndPushPickerView) forControlEvents:UIControlEventTouchUpInside];
    
    LHTopTextView *topTextView=[[LHTopTextView alloc]initWithFrame:CGRectMake(15, controller.view.bounds.size.height/3, controller.view.bounds.size.width-30, controller.view.bounds.size.height/3)];
    self.topTextView=topTextView;
    topTextView.submitBlock=^(NSString *text){
        [self popAndPushPickerView];
        if(self.requestDataBlock){
            self.requestDataBlock(text);
        }
    };
    topTextView.closeBlock=^(){
        [self popAndPushPickerView];
    };
    [self.grayBgView addSubview:topTextView];
    
}
return self;
}

+(instancetype)showWithController:(UIViewController *)controller{
LHEditTextView *editTextView=[[self alloc]initWithController:controller];
editTextView.controller=controller;
[controller.view addSubview:editTextView];
[editTextView popAndPushPickerView];
return  editTextView;
}

+(void)showWithController:(UIViewController *)controller andRequestDataBlock:(void(^)(NSString *text))requestDataBlock{
LHEditTextView *edit=[LHEditTextView showWithController:controller];
edit.requestDataBlock=requestDataBlock;
}

-(void)popAndPushPickerView{
if(self.grayBgView.hidden){
    [UIView animateWithDuration:0.5 animations:^{
        self.grayBgView.hidden=NO;
        self.topTextView.hidden=NO;
    }];
    [self.grayBgView setUserInteractionEnabled:YES];
}else{
    [UIView animateWithDuration:0.5 animations:^{
        self.topTextView.hidden=YES;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 animations:^{
            self.grayBgView.hidden=YES;
        }];
    }];
    
}

}

@end

呼叫還是十分簡單:ViewController.m

#import "ViewController.h"
#import "LHEditTextView.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[LHEditTextView showWithController:self andRequestDataBlock:^(NSString *text) {
    NSLog(@"這裡面去實現資料的回撥");
}];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

這是這兩天寫的小demo,其實有心的人會把這兩個demo封裝到一起的,這樣子今後用這也方便。。。。降龍十八掌,打完收工!
有想要demo的,可以加我QQ:635326856
最近我發現好多人問我要程式碼,但是我整天不開電腦,給你們說,第一種樣式其實很簡單,就是將上面的程式碼給複製下來生成對應名字的檔案(.h和.m檔案)就可以了。