如果您是一位幸运的开发者,并且只针对 iOS 8+ 设备,那么请享受新的 UIAlertController
,否则请看看 DAAlertController
,它会真正节省时间。
DAAlertController
提供了一个方便的基于块的界面来配置和展示 UIAlertView
和 UIActionSheet
。如果 UIAlertContoller
可用,则 DAAlertController
就会将所有工作交给它来处理,否则它将使用关联引用(稍后会详细介绍)在按钮被点击时调用手动处理程序,就像 UIAlertController
一样。
当然,DAAlertController
的功能有限,仅限于旧的 UIAlertView
和 UIActionSheet
可以做到。
要运行示例项目,克隆代码库,然后首先从 Example 目录运行 pod install
。
让我们看看简单的警告视图的例子
DAAlertAction *cancelAction = [DAAlertAction actionWithTitle:@"Cancel"
style:DAAlertActionStyleCancel handler:nil];
DAAlertAction *signOutAction = [DAAlertAction actionWithTitle:@"Sign out"
style:DAAlertActionStyleDestructive handler:^{
// perform sign out
}];
[DAAlertController showAlertViewInViewController:self
withTitle:@"Are you sure you want to sign out?"
message:@"If you sign out of your account all photos will be removed from this iphone."
actions:@[cancelAction, signOutAction]];
以下是 iOS 8 和 7 会得到的:(UIAlertView
不支持破坏性行为按钮,因此“签出”按钮将被渲染为默认按钮)
iOS 8+ | iOS 7 |
---|---|
![]() |
![]() |
展示包含 2 个文本字段(“注册”按钮应该在“昵称”至少有 5 个字母时启用)的警告视图将会这样
DAAlertAction *cancelAction = [DAAlertAction actionWithTitle:@"Cancel" style:DAAlertActionStyleCancel handler:nil];
DAAlertAction *signUpAction = [DAAlertAction actionWithTitle:@"Sign up" style:DAAlertActionStyleDefault handler:^{
// perform sign up
}];
[DAAlertController showAlertViewInViewController:self
withTitle:@"Sign up"
message:@"Please choose a nick name."
actions:@[cancelAction, signUpAction]
numberOfTextFields:2
textFieldsConfigurationHandler:^(NSArray *textFields)
{
UITextField *nickNameTextField = [textFields firstObject];
nickNameTextField.placeholder = @"Nick name";
UITextField *fullNameTextField = [textFields lastObject];
fullNameTextField.placeholder = @"Full name";
} validationBlock:^BOOL(NSArray *textFields) {
UITextField *nickNameTextField = [textFields firstObject];
return nickNameTextField.text.length >= 5;
}];
iOS 8+ | iOS 7 |
---|---|
![]() |
![]() |
展示操作表的方法相当类似,但还包含了 sourceView
或 barButtonItem
以及 permittedArrowDirections
等参数。
iOS 8+ | iOS 7 |
---|---|
![]() |
![]() |
![]() |
![]() |
DAAlertController 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。