Fetch Width and Height From UIView

How to fetch width and height of a UIView that is programatically added?

Code:

let View1: UIView = {

let viewView = UIView() viewView.translatesAutoresizingMaskIntoConstraints = false

        viewView.contentMode = .scaleAspectFit
        print(UserDefaults.standard.bool(forKey: "backgroundColourSelected"))

        if UserDefaults.standard.bool(forKey: "backgroundColourSelected") {
            viewView.backgroundColor = self.viewColor
        }else {
            viewView.backgroundColor = .white
        }
        viewView.clipsToBounds = true
        return viewView
    }()
    self.canvasView.addSubview(View1)
    View1.centerXAnchor.constraint(equalTo: canvasView.centerXAnchor, constant: 0).isActive = true
    View1.centerYAnchor.constraint(equalTo: canvasView.centerYAnchor, constant: 0).isActive = true
    View1.widthAnchor.constraint(equalTo: canvasView.widthAnchor, constant: 0).isActive = true
    View1.heightAnchor.constraint(equalTo: canvasView.widthAnchor, multiplier: aspectRatio).isActive = true

I want to get the final width and height by adding the above code programatically. Please help.

Doesn't

viewView.frame.size 

or

View1.frame.size

give you what you are looking for ?

Note: you should take care of your var naming:

  • should start with lowerCase as view1
  • get explicit names (viewView is not very much)

In the code you posted, you do not define a frame for viewView. Hence 0,0

I did some formatting:

let View1: UIView = {
        let viewView = UIView() 
        viewView.translatesAutoresizingMaskIntoConstraints = false
        viewView.contentMode = .scaleAspectFit
        print(UserDefaults.standard.bool(forKey: "backgroundColourSelected"))

        if UserDefaults.standard.bool(forKey: "backgroundColourSelected") {
            viewView.backgroundColor = self.viewColor
        } else {
            viewView.backgroundColor = .white
        }
        viewView.clipsToBounds = true
        return viewView
    }()

Try and replace

        let viewView = UIView() 

by something like:

        let viewView = UIView(frame: CGRect(x: 64, y: 0, width: 256, height: 128))
Fetch Width and Height From UIView
 
 
Q