今天来分享如何来自定义AlertController,大家可以按照我的方法封装各种各样的控件,相当简单可靠,需要调用只需要一行代码。
效果:
实现思路
创建工具类KYPickerView
工具类的目的是更方便的调用自定义AlertController。废话不多上,上代码。
/**
自定义选择器
@param target target
@param options Picker要显示的数据
@param title Alter的Title
@param block block
*/
+ (void)showPickerWithTarget:(id)target Options:(NSArray *)options title:(NSString *)title selectionBlock:(void (^)(NSString *selectedOption))block{
KYAlertPickerController *alertController = [KYAlertPickerController alertControllerWithTitle:title message:@"\n\n\n\n\n\n\n\n\n\n\n"preferredStyle:UIAlertControllerStyleActionSheet];
alertController.options = options;
alertController.pickerTitle = title;
[alertController setPickerDoneBlock:block];
[target presentViewController:alertController animated:YES completion:nil];
}
实现类KYAlertPickerController
KYAlertPickerController继承自UIAlertController,同时为了保证弹出的AlertView具有一定的高度,创建时可以用@"\n"来填充。显示出来的AlterView的结构大概如下图:
实现核心代码
- (void)initView {
self.toolbar = [[UIToolbar alloc] init];
self.toolbar.clipsToBounds = YES;
//自定义取消按钮,可自定义自己喜欢的样式
UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
cancelBtn.frame = CGRectMake(0, 5, 30, 30);
[cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cancelBtn addTarget:self action:@selector(pickerCancel:) forControlEvents:UIControlEventTouchUpInside];
[cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
cancelBtn.titleLabel.font = [UIFont systemFontOfSize:13];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]initWithCustomView:cancelBtn];
//自定义取消按钮,可自定义自己喜欢的样式
UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
doneBtn.frame = CGRectMake(0, 5, 30, 30);
[doneBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[doneBtn addTarget:self action:@selector(pickerDone:) forControlEvents:UIControlEventTouchUpInside];
[doneBtn setTitle:@"完成" forState:UIControlStateNormal];
doneBtn.titleLabel.font = [UIFont systemFontOfSize:13];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]initWithCustomView:doneBtn];
//空格
UIBarButtonItem *flexibleButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
//标题按钮
self.titleButton = [[UIBarButtonItem alloc] initWithTitle:self.pickerTitle style:UIBarButtonItemStylePlain target:nil action:nil];
self.titleButton.tintColor = [UIColor blackColor];
//设置UIToolBar
[self.toolbar setItems:@[cancelButton,flexibleButton,self.titleButton,flexibleButton,doneButton]];
//添加ToolBar
[self.view addSubview:self.toolbar];
[self createPickerView];
}
- (void)createPickerView {
self.pickerView = [[UIPickerView alloc] init];
self.pickerView.clipsToBounds = YES;
self.pickerView.dataSource = self;
self.pickerView.delegate = self;
self.pickerView.showsSelectionIndicator = YES;
[self.view addSubview:self.pickerView];
}
github下载地址:https://github.com/kangyiii/KYAlterPickerDemo
喜欢的话可以留下您的star哦~