UIAlertController and UIAlertControllerStyleActionSheet customization

前端 未结 2 468
耶瑟儿~
耶瑟儿~ 2021-01-06 04:47

I\'m trying to create a custom UIAlertController with style UIAlertControllerStyleActionSheet (formerly UIActionSheet) and I\'m encounterin

2条回答
  •  抹茶落季
    2021-01-06 05:23

    This solution does use private APIs/properties. Based my research and experience, this is the only way I know that you can customize UIAlertController. If you look at the public header, UIAlertContoller has little room for customization. However, this solution is commonly used among developers after the launch of UIAlertController in iOS 8. You can totally rely on depedencies from Github. I hope my answer can solve your problem. I believe this is what you are looking for, the result loooks like this:

    First, you have to create a UIAlertController

    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Alert Title" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    

    Custom font! even for just certain characters.

    NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Presenting the great... StackOverFlow!"];
    [hogan addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0] range:NSMakeRange(24, 11)];
    [alertVC setValue:hogan forKey:@"attributedTitle"];
    

    Now, let's create a UIAlertAction, where you can add action handlers and also add icons.

    UIAlertAction *button = [UIAlertAction actionWithTitle:@"First Button"
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction *action){
                                                       //add code to make something happen once tapped
                                                   }];
    UIAlertAction *button2 = [UIAlertAction actionWithTitle:@"Second Button"
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction *action){
                                                       //add code to make something happen once tapped
                                                   }];
    

    Here, you add the icon to the AlertAction. For me, you have to specify UIImageRenderingModeAlwaysOriginal

    [button setValue:[[UIImage imageNamed:@"image.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"image"];
    
    [alertVC addAction:button2];
    [alertVC addAction:button];
    

    Remember to present the ViewController

    [self presentViewController:alertVC animated:YES completion:nil];
    

提交回复
热议问题