Customize UIAlertController in iOS 8 to include standard elements like UITableView

不羁的心 提交于 2019-11-29 22:24:21

I ran into the same issue right now. I looked at the private header for UIAlertController (https://github.com/nst/iOS-Runtime-Headers/blob/master/Frameworks/UIKit.framework/UIAlertController.h) and found a promising property: contentViewController

And it turned out to be exactly the same as accessoryView used to be for UIAlertView, the difference being that you need to assign a UIViewController to this property rather than a UIView.

UIViewController *v = [[UIViewController alloc] init];
v.view.backgroundColor = [UIColor redColor];

[alertController setValue:v forKey:@"contentViewController"];

That piece of code will show a red view on the alert view! Happy UIAlertController customizing ;)

PS. It is a private property but using KVC there shouldn't be a problem App Store wise, I think.

Edit:

Some people complained that this isn't very safe. It's not a public API, so yes, Apple could change it in any release, causing this method to fail.

To make sure your entire app doesn't crash if that happens you could wrap the KVC call in a try block. If the property changes your controller won't show the content view, but it also won't crash:

@try {
    [alertController setValue:v forKey:@"contentViewController"];
}
@catch(NSException *exception) {
    NSLog(@"Failed setting content view controller: %@", exception);
}

Using this method in production can be risky, and I don't recommend it for important alerts.

Adam Kaplan

I suggest not your wasting time trying to cram additional UI into a place where isn't supposed to be. Based on the last few years of improvements, Apple will probably add a custom view in the next iOS. Until then, have a look at a framework designed to handle this exact situation without subverting any best practices: SDCAlertView

It supports alerts that imitate the native alerts on iOS 7,8,9, including handling all of the nasty edge cases around sizing, button types, rotation, etc. It does support arbitrary custom views within the alert.

I use this library in Yahoo YMPromptKit for custom push notification prompts that look exactly like iOS native. Here's another example:

CyberInfo

I think you can easily customize the UIView adding the controls needed and present it modally, unless you have any other specific reason to use only UIAlertController.

https://www.cocoacontrols.com/search?q=UIAlertview

mientus

You can do it with just a one of line of code using my UIAlertController category and replace existing alerts in application, check it here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!