1

EDIT: added a snapshot.

I have a UIView class, as follows..

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
    }

in a different .swift file, I have the following 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


    }


}

Is there a reason why it's not working in the second case?

instanceOfCreateNewUserView.center.y = view.center.y

also, the following doesn't work..

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

The app builds and runs, however, the view is aligned horizontally, but not vertically.

I'm new to swift and trying to figure out how to build/ align control elements programmatically.enter image description here

Gamal Elsayed
  • 63
  • 2
  • 10

1 Answers1

0

Your view hierarchy looks like this:

CreateNewUserVC's view
----- subVu

The CreateNewUserView is not involved at all, you never added it to the view controller's view.

Hence moving its frame doesn't change the layout of any views on the screen.

Tristan Burnside
  • 2,546
  • 1
  • 16
  • 23
  • But if that's the case, why does it work when I run the function?? Yet, it doesn't work using access to the .center property..? If the view is not involve, why is it affected with one approach, but not the other..? Could you elaborate..? Thanks. – Gamal Elsayed Jul 15 '17 at 08:26
  • 1
    The function changes the frame of `subVu` which is displayed. The other line changes the frame of `instanceOfCreateNewUserView` which is not on screen – Tristan Burnside Jul 15 '17 at 08:29
  • Thank you. This corrected my approach. I should alter using a call to the function that returns a UIView, not an instance of a class. Appreciate the hint. – Gamal Elsayed Jul 15 '17 at 08:35