我正在从代码构建我的 UI,并且需要在当前 Controller 上呈现另一个 View Controller 作为弹出窗口。弹出窗口将充当模式对话框,并将使用大约 50% 的屏幕尺寸。弹出窗口的内容必须限制在屏幕中心并支持设备旋转。
我的初始实现是在 PopoverController 类的 viewDidLoad() 中完成的,并且它按预期工作。但是,我不想在我的 Controller 中查看代码。将弹出窗口 View 移动到单独的文件后,乐趣就开始了;自动布局和设备旋转不再按预期工作。
我制作了一个基本的应用程序来展示这一点。主 Controller 有一个用于显示弹出窗口的按钮。弹出窗口具有黄色背景,并且应在中心显示蓝色 View 。
MainViewController::用于显示弹出窗口的测试按钮
@objc func boxButtonTapped() {
let vc = PopoverController()
vc.modalPresentationStyle = .overCurrentContext
vc.modalTransitionStyle = .crossDissolve
present(vc, animated: true, completion: nil)
}
弹出 Controller
class PopoverController: UIViewController {
var popoverView = PopoverView()
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadView() {
view = popoverView
}
}
弹出 View
class PopoverView: UIView {
let blueBox: UIView = {
let bb = UIView()
bb.backgroundColor = .blue
//bb.frame.size = CGSize(width: 100, height: 100)
bb.translatesAutoresizingMaskIntoConstraints = false
return bb
}()
override init(frame: CGRect) {
super.init(frame: frame)
createSubViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
createSubViews()
}
func createSubViews() {
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = .yellow
addSubview(blueBox)
blueBox.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
blueBox.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
blueBox.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.7).isActive = true
blueBox.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.4).isActive = true
}
}
运行上述代码时,弹出窗口甚至不显示!这是我的第一个问题,有人能明白为什么吗?
如果我将translatesAutoresizingMaskIntoConstraints = false 更改为true。然后会显示弹出窗口,但当设备旋转时它不会调整大小。我不知道为什么,也不明白为什么需要将 TranslatesAutoresizingMaskIntoConstraints 设置为 true 才能首先显示 View 。
对于如此琐碎的任务,必须有一个简单的解决方案。我已经尝试了很多不同的方法,在这里列出它们是不可能的。我是 IOS 开发和 Swift 的新手,我真的很想以干净的代码开始一个良好的开端。感谢您的宝贵时间!
更新 我在 GitHub 上发布了示例项目。因此,如果您有时间并想要挑战/证明一个概念,那么这里是:https://github.com/igunther/CleanController
最佳答案
如果您没有自己添加约束(在本例中您没有添加约束),您仍然需要告诉 View 如何行为。
将您的 createSubviews()
函数更改为:
func createSubViews() {
//translatesAutoresizingMaskIntoConstraints = false
autoresizingMask = [.flexibleHeight, .flexibleWidth]
backgroundColor = .yellow
addSubview(blueBox)
blueBox.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
blueBox.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
blueBox.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.7).isActive = true
blueBox.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.4).isActive = true
}
这将允许自动布局在设备旋转时重新布局您的 View 。
关于ios - 使用自动布局以编程方式呈现弹出 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55715322/