2016-06-22 48 views
1

通過引用線程https://stackoverflow.com/a/32790860,我通過xib創建了一個自定義視圖(其類爲「CustomViewForAlert」),並將其添加到警報控制器,其中包含以下內容碼。通過XIB向UIAlertController添加自定義視圖,但佈局不如預期

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

然而,得到的佈局就奇怪如下。

resulting layout screenshot, 可以發現動作按鈕向上移動,並且視圖(來自XIB,藍色背景)比警報控制器更寬。 我該如何解決它?謝謝!!

回答

0

您可以編輯你的代碼是這樣

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) 
相關問題