swiftxcodeuiviewboundscgsize

How to get UIView height and width in Swift? (problem: returning zero)


Sorry in advance for the probably silly question - I'm a beginner

I'm generating a new UIView in viewDidLoad, providing some constraints to anchor it over the main view. When it comes to understand the size of the new view, I always get zero.

Here is a simplified version of my code which is not working:

    override func viewDidLoad() {
    super.viewDidLoad()
    
    let myView = UIView(frame: .zero)
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)
    myView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    myView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -200).isActive = true
    myView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    myView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    print(myView.bounds.width)
    
}

The width (but also height) is returning 0. This happens both with .bounds and .frame. Do you have any hints? Thanks!


Solution

  • First question I will ask, does the UIView display on the screen?

    Second, from the knowledge of view controller life cycle, the views are laid out in viewDidLayout Subviews.

    So, you want to called myView.bounds.width in by overriding the viewDidLayout Subviews or viewDidAppear, when the views have finally appeared in the screens

    Thanks for making the question more clear.

    I will suggest you either reloadData on the second collection view on viewDidLayout subviews. That way, the two gets layout as it is now, then the second collection view gets layout for the second time after the first collection view is laid.

    Another approach will be for you to use relative constraints. I.e. Making weight and height constraints of the items in the second collection view relative to the items in the first collection view. This way, everything else is done automatically for you at runtime. Even if the size of the items in first collection view change later which might affect items of the second collection view, it will be taken care off. (For accurate result if you can get it to work)

    I will appreciate if you can share more of the code or screen shots of these two collections views. I could provide a better approach to creating them