效果图
思路是依靠 UIalertController的高度是由内容判定,修改其view 即可
首先不需要改变该类的初始化(因为只是修改其view的界面)
继承UIalertController的.h文件
#import <UIKit/UIKit.h> typedef void(^BlockDate)(id date); @interface SheetDate : UIAlertController @PRoperty(nonatomic,copy)BlockDate blockDate; @property(retain,nonatomic)UIDatePicker* datePicker; /** * 单例 */ +(SheetDate *)defaultSheetDate; @end
继承UIalertController的.m文件
#import "SheetDate.h" @interface SheetDate () @end @implementation SheetDate - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /** * 添加日期控件 */ -(void)addDatePicker { self.datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 216)]; self.datePicker.datePickerMode = UIDatePickerModeDate; self.datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]; [self.view addSubview:self.datePicker]; } /** * 处理日期数据 * * @return */ -(NSString*)dealDate { NSDateFormatter * formatter = [[NSDateFormatter alloc ] init]; if (self.datePicker.datePickerMode==UIDatePickerModeTime) { [formatter setDateFormat:@"HH:ss"]; } else if(self.datePicker.datePickerMode==UIDatePickerModeDate) { [formatter setDateFormat:@"YYYY-MM-dd"]; } else if(self.datePicker.datePickerMode==UIDatePickerModeDateAndTime) { [formatter setDateFormat:@"YYYY-MM-dd HH:ss"]; } NSString* currentTime = [formatter stringFromDate:self.datePicker.date]; return currentTime; } /** * 单例 * * @return */ +(SheetDate *)defaultSheetDate { //sheetDate只会实例化一次 static SheetDate* sheetDate=nil; //保证线程安全,defaultSheetDate只执行一次 static dispatch_once_t once; dispatch_once(&once, ^ { sheetDate=[SheetDate alertControllerWithTitle:nil message:@"\n\n\n\n\n\n\n\n\n\n\n" preferredStyle:(UIAlertControllerStyleActionSheet)]; [sheetDate addDatePicker]; UIAlertAction* ok=[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * __nonnull action) { sheetDate.blockDate([sheetDate dealDate]); }]; [sheetDate addAction:ok]; }); return sheetDate; }
添加的日期控件是以属性形式添加的,可以根据情况配置。
首先使用系统的方法创建uialertcontroller对象,使用\n是因为需要扩大显示的高度,然后调用[sheetDate addDatePicker]添加自定义界面,根据情况初始化使用日期数据的block
然后在sheet的选项中触发就可以了。
然后是使用
/** * 选择日期时间 * * @param sender */ - (IBAction)chooseDate:(UIButton *)sender { SheetDate* sheetDate=[SheetDate defaultSheetDate]; sheetDate.datePicker.datePickerMode=UIDatePickerModeDateAndTime; sheetDate.blockDate=^(NSString* date) { NSLog(@"%s\n%@",__FUNCTION__,date); [sender setTitle:date forState:(UIControlStateNormal)]; }; [self presentViewController:sheetDate animated:YES completion:nil]; }