1

By referring to the thread https://stackoverflow.com/a/32790860, I made a custom view (whose class is "CustomViewForAlert") via xib and added it to an alert controller with the following codes.

let alertController = UIAlertController(title: "\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.Alert)

let margin:CGFloat = 8.0
let alertViewNib = UINib(nibName: "CustomViewForAlert", bundle: nil)
let customViewForAlert = alertViewNib.instantiateWithOwner(nil, options: nil)[0] as! CustomViewForAlert
let rect = CGRectMake(margin, margin, alertController.view.bounds.size.width - margin * 4.0, 300.0)
customViewForAlert.frame = rect
alertController.view.addSubview(customViewForAlert)

let somethingAction = UIAlertAction(title: "act 1", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in println("something")})
let cancelAction = UIAlertAction(title: "act 2", style: UIAlertActionStyle.Cancel, handler: {(alert: UIAlertAction!) in println("cancel")})

alertController.addAction(cancelAction)
alertController.addAction(somethingAction)

self.presentViewController(alertController, animated: true, completion:{})

However, the resulting layout went weird as follow.

In the resulting layout screenshot, it can be found that the action buttons were shifted upward, and the view (from XIB, with a blue background) was wider than the alert controller. How could I fix it? Thank you!!

Community
  • 1
  • 1

1 Answers1

0

You can edit your code to be like this

let alertController = UIAlertController(title: "\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let margin:CGFloat = 8.0
let rect = CGRectMake(margin, margin, alertController.view.bounds.size.width - margin * 4.0, 300.0)
let customViewForAlert = UIView(frame: rect)
alertController.view.addSubview(customViewForAlert)

let somethingAction = UIAlertAction(title: "act 1", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in println("something")})
let cancelAction = UIAlertAction(title: "act 2", style: UIAlertActionStyle.Cancel, handler: {(alert: UIAlertAction!) in println("cancel")})

alertController.addAction(cancelAction)
alertController.addAction(somethingAction)

self.presentViewController(alertController, animated: true, complition: nil)
techspider
  • 3,370
  • 13
  • 37
  • 61
Ali Safaya
  • 56
  • 9