【问题标题】:UIAlertController: addSubviewUIAlertController:添加子视图
【发布时间】:2017-08-17 13:16:51
【问题描述】:

我想向我的警报控制器添加一个子视图。但是为什么按钮在顶部呢?我该如何解决这个问题?

    let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.alert)

    let somethingAction = UIAlertAction(title: "Something", style: .default, handler: {(alert: UIAlertAction!) in print("something")})

    let cancelAction = UIAlertAction(title: "Annuler", style: .cancel, handler: {(alert: UIAlertAction!) in print("cancel")})

    alert.addAction(somethingAction)
    alert.addAction(cancelAction)

    let customView = UIView()
    customView.backgroundColor = .green
    customView.translatesAutoresizingMaskIntoConstraints = false
    customView.widthAnchor.constraint(equalToConstant: 128).isActive = true
    customView.heightAnchor.constraint(equalToConstant: 128).isActive = true

    alert.view.addSubview(customView)

    customView.centerXAnchor.constraint(equalTo: alert.view.centerXAnchor).isActive = true
    customView.topAnchor.constraint(equalTo: alert.view.topAnchor).isActive = true
    customView.bottomAnchor.constraint(equalTo: alert.view.bottomAnchor, constant: -32).isActive = true
    self.present(alert, animated: true, completion:{})

【问题讨论】:

  • UIAlertController 不支持添加子视图。如果您想要自定义警报,请使用自定义警报,而不是 UIAlertController
  • @RajeshkumarR 谢谢,但他使用了很多“/n”。但是我的视图高度是动态的,所以这对我来说不是一个好的解决方案。
  • 然后创建 UIView 并像 alertController 一样设计。

标签: ios swift uialertcontroller


【解决方案1】:

UIAlertController 是一个非常封闭的系统。它被设计为系统标准警报。您不应该向其中添加子视图。

我会创建一个自定义 UIViewController 来充当警报。您可以使用自定义 UIViewController 转换以与 UIAlertController 相同的方式显示。

还有许多 GitHub 项目提供您可能喜欢的自定义警报样式。比如这个:https://github.com/DominikButz/DYAlertController

【讨论】:

  • 感谢您的回答:)
  • 很高兴它有帮助!快乐编码:)
猜你喜欢
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多