Custom View in UIAlertController

tentmaking picture tentmaking · Apr 19, 2017 · Viewed 11k times · Source

I am trying to put a custom view inside a UIAlertController. I'm running into some odd issues with the sizing of the custom view.

I want the custom view to span the width of the UIAlertController, whatever that might be. I'm using CGRectGetWidth(alertController.view.bounds) to get the width of the alert controller. However, this seems instead to be returning the width of the entire view. using view.frame does not make a difference.

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"My Title" message:nil preferredStyle:UIAlertControllerStyleAlert];

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(alertController.view.bounds), 50)];
view.backgroundColor = [UIColor blueColor];

[alertController.view addSubview:view];
[self presentViewController:alertController animated:YES completion:nil];

This yields the results below. I have the same issue trying to get X, Y width and height properties of the UIAlertController. Does anyone know how I can position this view in the middle of the alert controller without using hard-coded numbers?

enter image description here

Answer

Duncan C picture Duncan C · Apr 19, 2017

You're not supposed to do that. To quote the docs:

The UIAlertController class is intended to be used as-is and does not support subclassing.

The view hierarchy for this class is private and must not be modified.

If you go against an explicit statement like that from Apple all bets are off, and even if you can get it to work on the current OS version, it could break with any future version.