2

I have been banging my head a against the wall for a while now:

How can I get the width of a UIAlertController action sheet's view?

Saying alert.view.frame.width gives view.frame.width.

Also, I saw this question, but it simply does not work: it just changes the frame of the alert, and I don't see how I can get the width from it.

Thanks in advance.

Community
  • 1
  • 1
IHaveAQuestion
  • 789
  • 8
  • 26

3 Answers3

1

The width of the .actionSheet type UIAlertController is the width of the UIWindow (in portrait mode) minus 10 points of padding on each side, irregardless of the device orientation.

E.g. in the case of an iPhone 7, which has a width of 375 points:

enter image description here

Unsurprisingly, 355 points is the same value I get from alert.view.frame.width, given that the value is accessed in the completion block of present(_:​animated:​completion:​), i.e. after the view has appeared.

xoudini
  • 7,001
  • 5
  • 23
  • 37
0

xoudini's Answer is definitely a solution. But a disadvantage could be the little delay of adding the custom view with the right width in the completion block. See the gif:

enter image description here

So an alternative solution could be, just to use this extension for UIDevice and then by checking the modelName, you can set the width values of the the action sheet of the different devices (maybe a little bit hacky, but you would avoid the delay and can set the width before the completion block). Here are the different width sizes of the action sheets of the currently supported devices of iOS10:

  • iPhone5/iPhone5s/iPhoneSE: 300
  • iPhone6/iPhone6s/iPhone7: 355
  • iPhone6Plus/iPhone6sPlus/iPhone7Plus: 394

  • iPad 9.7/12.9/Retina/Air1/Air2: 300

Community
  • 1
  • 1
ronatory
  • 7,156
  • 4
  • 29
  • 49
-1

Though I am late here, but better late than never.

Width for alert view controller is set in constraints. To get the width of the alert controller, you can use:

for constraint in self.alertView.subviews[0].constraints {

  if constraint.firstAttribute == NSLayoutAttribute.width {
  print("\(constraint.constant)")
  break
  }
}
HeadOnn
  • 1,480
  • 14
  • 21