首页 > 解决方案 > 约束在 Present ViewController 中无法正常工作

问题描述

我有一个像 PopUp 这样的 ViewController,但 View 没有保持在我想要的位置。

我希望这个视图保持在屏幕的中心。下面的屏幕显示了情节提要中的视图,其中设置了约束和模拟器上的结果。

在此处输入图像描述

AlertViewController.swift

class AlertViewController : UIViewController {

    @IBOutlet weak var frameView: UIView!
    @IBOutlet weak var btCancel: UIButton!
    @IBOutlet weak var lblInfo: UILabel!

    var delegate : AlertViewControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()        
        self.frameView.layer.cornerRadius = 10
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }

    @IBAction func cancel(_ sender: Any) {
        delegate?.cancelBt()
        self.dismiss(animated: true, completion: nil)
    }
}

MainViewController.swift (显示)

let alertController = self.storyboard?.instantiateViewController(withIdentifier: "AlertVC") as! AlertViewController
            alertController.providesPresentationContextTransitionStyle = true
            alertController.definesPresentationContext = true
            alertController.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
            alertController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
            alertController.delegate = self

            self.present(alertController, animated: true, completion: {})

编辑

我试过这个。

在此处输入图像描述

结果:(我确实改变了背景颜色)。

在此处输入图像描述

标签: iosswiftxcodelayoutconstraints

解决方案


您的问题是使用静态值设置顶部、底部、前导和尾随约束,当您在设备中运行时可能会中断,您需要设置

宽度,高度,centerX,centerY

* 使宽度和高度与屏幕成正比的良好做法,乘数或内容大小取决于 *

顶部标签

顶部,中心X

活动

顶部到标签,centerX

中间标签

中心X,Y

取消按钮

中心X,底部


推荐阅读