将 UIPickerView 放在 UIAlertController 的中心

Posted

技术标签:

【中文标题】将 UIPickerView 放在 UIAlertController 的中心【英文标题】:Place UIPickerView in the centre of the UIAlertController 【发布时间】:2018-12-25 13:41:45 【问题描述】:

如何将 UIPickerView 放置在 UIAlertController 的中心?

现在我有了这个代码:

let alertController = UIAlertController(title: "Представьтесь пожалуйста", message: "Кто вы?", preferredStyle: .alert)
alertController.isModalInPopover = true
userTypePickerView = UIPickerView(frame: CGRect(x: 0,
                                                y: 0,
                                                width: alertController.view.bounds.size.width,
                                                height: 140))
userTypePickerView.delegate = self
userTypePickerView.dataSource = self
let height: NSLayoutConstraint = NSLayoutConstraint(item: alertController.view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 240)
alertController.view.addConstraint(height)
alertController.view.addSubview(userTypePickerView)

我看到了这张照片……

【问题讨论】:

你不应该那样做。来自文档:Important The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified. 但可以做到,有点我不知道怎么做:( @ДмитрийДеникаев 可以做到,但正如@Desdenova 所说,不要这样做,因为如果Apple 决定更改UIAlertController 的视图层次结构,您可能会在未来的ios 更新中遇到问题。而是为此创建自定义警报。 @NajdanTomić 嗯,这是真的,谢谢,我会做的。 【参考方案1】:

尽管我投票赞成创建自定义警报,但您可以这样做

let alertController = UIAlertController(title: "Представьтесь пожалуйста", message: "Кто вы?", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "ok", style: .default, handler: nil))
alertController.isModalInPopover = true
let userTypePickerView = UIPickerView(frame:.zero)
 alertController.view.addSubview(userTypePickerView)
userTypePickerView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    userTypePickerView.widthAnchor.constraint(equalToConstant: 200),
    userTypePickerView.heightAnchor.constraint(equalToConstant: 200),
    userTypePickerView.topAnchor.constraint(equalTo: alertController.view.topAnchor,constant:70),
    userTypePickerView.bottomAnchor.constraint(equalTo: alertController.view.bottomAnchor,constant:-40),
    userTypePickerView.centerXAnchor.constraint(equalTo: alertController.view.centerXAnchor)
])
userTypePickerView.backgroundColor = .red
self.present(alertController, animated: true, completion: nil)

【讨论】:

我想你忘记了userTypePickerView.centerYAnchor.constraint(equalTo: alertController.view.centerYAnchor,我在我的代码中添加了这一行,它对我有帮助。谢谢。

以上是关于将 UIPickerView 放在 UIAlertController 的中心的主要内容,如果未能解决你的问题,请参考以下文章

可以将 UIPickerView 放在 UIAlertView 之前吗?

为啥 UIPickerView 是半透明的

UIPickerView 选择和隐藏

如何防止在拖动 UIPickerView 时触发按钮?

如何将 UIPickerView 选定的行发送到另一个 ViewController

UIPickerView 改变框架的大小和位置