弹出窗口根据方向调整大小



我有根据设备方向制作可调整大小的弹出窗口的任务。我像这样在窗口上实例化它。

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 相当陌生,并且没有在代码中做很多约束。文章也会有所帮助。基本上每一个帮助都是受欢迎的。

提前谢谢。

你需要这个到你的弹出视图,它会自动调整大小

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)

请参考以下代码:

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
    }

最新更新