我已指派根据设备方向进行可调整大小的弹出窗口。我正在像这样在窗口上实例化它。
let window = UIApplication.shared.keyWindow
let popOver = DeletePopUpViewController(nibName: "DeletePopUpViewController", bundle: nil)
popOver?.loadViewIfNeeded()
popOver?.view.frame = window!.frame
window?.addSubview(popOver!.view)
我在IB中增加了约束,因为目前我的任务无法调整大小。现在,我需要将约束转移到代码上,这使我感到困扰。我能够使用-
这样的观察器检测方向变化NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
@objc private func rotated() {
if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft || UIDevice.current.orientation == UIDeviceOrientation.landscapeRight {
//code to implement constraints and size in landscape.
}
if UIDevice.current.orientation == UIDeviceOrientation.portrait || UIDevice.current.orientation == UIDeviceOrientation.portraitUpsideDown {
//code to implement constraints and size in portrait.
}
}
由于我对Swift相当陌生,并且没有在代码中进行很多约束,因此请您给我一些指导。另外,文章也将有所帮助。基本上,每一个帮助都是值得欢迎的。
谢谢。
答案 0 :(得分:0)
请参考以下代码:
let window = UIApplication.shared.keyWindow
let popOver = DeletePopUpViewController(nibName: "DeletePopUpViewController", bundle: nil)
popOver?.loadViewIfNeeded()
popOver.tag = 1000
popOver?.view.frame = window!.frame
window?.addSubview(popOver!.view)
@objc private func rotated() {
let window = appDelegate.window!
if let popup = window.viewWithTag(1000){
popup.frame = window.bounds
}
}
更新:具有自动版式
func addPopoverView(){
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let rootVC = appDelegate.window?.rootViewController else {
return
}
let viewToAdd = UIView()
let count = rootVC.view.subviews.count
rootVC.view.insertSubview(viewToAdd, at: count)
viewToAdd.translatesAutoresizingMaskIntoConstraints = false
viewToAdd.leadingAnchor.constraint(equalTo: rootVC.view.leadingAnchor, constant: 0).isActive = true
viewToAdd.trailingAnchor.constraint(equalTo: rootVC.view.trailingAnchor, constant: 0).isActive = true
viewToAdd.topAnchor.constraint(equalTo: rootVC.view.topAnchor, constant: 0).isActive = true
viewToAdd.bottomAnchor.constraint(equalTo: rootVC.view.bottomAnchor, constant: 0).isActive = true
viewToAdd.backgroundColor = UIColor.red
}
答案 1 :(得分:0)
您需要在Popview中使用它,它将自动调整大小
let popOver = DeletePopUpViewController(nibName: "DeletePopUpViewController", bundle: nil)
popOver?.loadViewIfNeeded()
popOver?.autoresizingMask = [.flexibleHeight, .flexibleWidth, .flexibleTopMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleBottomMargin]
popOver?.view.frame = window!.frame
window?.addSubview(popOver!.view)