UIActionSheet 与alertview相似,同样也是弹框提示,不同的地方在于actionsheet是靠底端显示,而alertview是居中显示。
// 方法1 无代理,只有2个确定按钮
UIActionSheet *actionsheet01 = [[UIActionSheet alloc] initWithTitle:@"按钮点击后我才出现的。" delegate:nil cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:@"知道了", nil];
// 显示
[actionsheet01 showInView:self.view];
// 方法2 无代理,有多个确定按钮
UIActionSheet *actionsheet02 = [[UIActionSheet alloc] initWithTitle:@"按钮点击后我才出现的。" delegate:nil cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:@"知道了0", @"知道了1", @"知道了2", @"知道了3", nil];
// 显示
[actionsheet02 showInView:self.view];
// 方法3 有代理,有2个确定按钮
/*
1 设置代理为 self
2 添加协议
3 实现方法
*/
UIActionSheet *actionsheet03 = [[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册", @"拍照", nil];
// 显示
[actionsheet03 showInView:self.view];
// 添加协议
@interface ViewController () <UIActionSheetDelegate>
@end
// UIActionSheetDelegate实现代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(@"buttonIndex=%ld", buttonIndex);
// 方法1
// if (0 == buttonIndex)
// {
// NSLog(@"点击了相册按钮");
// }
// else if (1 == buttonIndex)
// {
// NSLog(@"点击了拍照按钮");
// }
// else if (2 == buttonIndex)
// {
// NSLog(@"点击了取消按钮");
// }
// 方法2
NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
BOOL isTakePhoto = [title isEqualToString:@"拍照"];
BOOL isPhotos = [title isEqualToString:@"相册"];
if (isTakePhoto)
{
NSLog(@"点击了拍照按钮");
}
else if (isPhotos)
{
NSLog(@"点击了相册按钮");
}
else
{
NSLog(@"点击了取消按钮");
}
}
// 方法4
/*
iOS8以后出现了UIAlertController视图控制器,通过设置UIAlertController的style属性来控制是alertview还是actionsheet
*/
UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:nil message:@"选择图片" preferredStyle:UIAlertControllerStyleActionSheet];
// 响应方法-取消
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了取消按钮");
}];
// 响应方法-相册
UIAlertAction *takeAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了相册按钮");
}];
// 响应方法-拍照
UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了拍照按钮");
}];
// 添加响应方式
[actionSheetController addAction:cancelAction];
[actionSheetController addAction:takeAction];
[actionSheetController addAction:photoAction];
// 显示
[self presentViewController:actionSheetController animated:YES completion:nil];