在另一个内部居中对齐的 UIView 无法以编程方式工作

Center-aligning UIView inside another is not working -programmatically-

编辑:添加了快照。

我有一个UIViewclass,如下..

class CreateNewUserView: UIView{

private let subVu: UIView! = UIView()

    func createNewUserVuLayout() -> UIView{
        subVu.frame.size =  CGSize(width:320, height:320)

    //  adding programmatically-created buttons, labels, textfields, etc..

        return subVu

    }

// will call the function below in a different ViewController class

func centerTheVu(superVuX:CGFloat){ 

        subVu.center.x = superVuX
    }

在不同的 .swift 文件中,我有以下 UIViewController class..

import UIKit

class CreateNewUserVC: UIViewController{

private let instanceOfCreateNewUserView = CreateNewUserView()


    override func loadView(){

        super.loadView()

        view.addSubview(instanceOfCreateNewUserView.createNewUserVuLayout())

// Calling the function from the UIView class now. Working perfectly!
// the view is centered horizontally as expected.        

instanceOfCreateNewUserView.centerTheVu(superVuX: view.center.x)

// However, if I delete the above line, the line below does not accomplish 
// the same task when I try to do the same vertically! 

        instanceOfCreateNewUserView.center.y = view.center.y


    }


}

在第二种情况下它不起作用的原因是什么?

instanceOfCreateNewUserView.center.y = view.center.y

此外,以下内容不起作用..

instanceOfCreateNewUserView.center.y = self.view.center.y

应用程序构建并运行,但是,视图是水平对齐的,而不是垂直对齐的。

我是 swift 的新手,正在尝试了解如何以编程方式构建/对齐控件元素。

您的视图层次结构如下所示:

CreateNewUserVC 的视图
----- subVu

根本不涉及 CreateNewUserView,您从未将其添加到视图控制器的视图中。

因此移动它的框架不会改变屏幕上任何视图的布局。