2016-06-22 13 views
1

Mit Verweis auf den Thread https://stackoverflow.com/a/32790860, machte ich eine benutzerdefinierte Ansicht (wessen Klasse ist "CustomViewForAlert") über Xib und fügte sie zu einem Alert-Controller mit den folgenden Codes.Benutzerdefinierte Ansicht von XIB zu UIAlertController hinzufügen, aber das Layout war nicht wie erwartet

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:{}) 

Allerdings ging das resultierende Layout seltsam wie folgt.

In den resulting layout screenshot, kann festgestellt werden, dass die Aktionstasten nach oben verschoben wurden, und die Ansicht (von XIB, mit einem blauen Hintergrund) war breiter als der Alarm-Controller. Wie könnte ich es beheben? Vielen Dank!!

Antwort

0

Sie können den Code sein wie diese

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) 
bearbeiten