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?
Here's an alternative.It's not adding subview to
UIAlertControl
's view hierarchy, but toUIWindow
instead in appropriate position. To trackUIAlertControl
's view frame the view controller is extended with a custom .view getter using obj-c runtime/swift extension which callsUIViewController
super class implementation. This allows avoiding genuine view's private class dependence and is neither subclassingUIAlertControl
or modifying it's view hierarchy.Example screenshot
Objective-C
Swift 3.1
You're not supposed to do that. To quote the docs:
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.