通过XIB将自定义视图添加到UIAlertController,但布局不符合预期

时间:2016-06-22 10:15:20

标签: swift view xib uialertcontroller

通过引用线程https://stackoverflow.com/a/32790860,我通过xib创建了一个自定义视图(其类为" CustomViewForAlert"),并将其添加到具有以下代码的警报控制器中。

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,具有蓝色背景)比警报控制器更宽。 我该怎么办呢?谢谢!!

1 个答案:

答案 0 :(得分: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)