gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:35:09 25 4
gpt4 key购买 nike

通过引用线程https://stackoverflow.com/a/32790860 ,我通过 xib 创建了一个自定义 View (其类为“CustomViewForAlert”),并使用以下代码将其添加到警报 Controller 中。

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 ,可以发现操作按钮向上移动,并且 View (来自 XIB,蓝色背景)比警报 Controller 更宽。我该如何解决?谢谢!!

最佳答案

你可以像这样编辑你的代码

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)

关于swift - 通过 XIB 将自定义 View 添加到 UIAlertController,但布局不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37965039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com