以编程方式将根视图添加到视图控制器未正确定位

时间:2017-03-31 16:51:18

标签: swift uiview uiviewcontroller

我正在尝试以编程方式将根视图和子视图添加到viewcontroller,但视图未按预期填充到屏幕:

override func loadView() {
        self.view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        self.view.backgroundColor = UIColor.blue
    }

    override func viewDidLoad() {

        let alertView = Bundle.main.loadNibNamed("CHRApptTakenAlertView", owner: self, options: nil)![0] as! CHRApptTakenAlertView

        self.view.translatesAutoresizingMaskIntoConstraints = false
        alertView.translatesAutoresizingMaskIntoConstraints = false

        self.view.addSubview(alertView)
        self.view.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0))
        self.view.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        alertView.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.width, multiplier: 1, constant: 350))
        alertView.addConstraint(NSLayoutConstraint(item: alertView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 250))

        alertView.closeBtn.addTarget(self, action: #selector(self.closeBtnTouch), for: UIControlEvents.touchUpInside)
    }

1 个答案:

答案 0 :(得分:0)

删除self.view.translatesAutoresizingMaskIntoConstraints = false行,并在添加约束后调用self.view.layoutIfNeeded()。