Yagiz Ozen
Yagiz Ozen

Reputation: 41

Swift 4 - How to get bounds of a UIView after Using Constraints Programatically

I really need your help about this issue. I am creating a UIView object programatically without setting the bounds at the beggining. After creating I add constraints to that view in order to fit the required place in the screen.

But the problem is that, I want to use that UIView's bounds property in the following parts of the code but unfortunately I can not get the bounds after constraints sets as it shows on the screen.

Below I have sample code :

     let previewView = UIView()

     NSLayoutConstraint(item: previewView, attribute: .top, relatedBy: .equal, toItem: upperView, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true

     NSLayoutConstraint(item: previewView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true


    previewView.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true

    previewView.translatesAutoresizingMaskIntoConstraints = false


    print(previewView.bounds)
   // (0.0, 0.0, 0.0, 0.0) ->>>> How can I get the bounds as it shows on the screen instead of 0,0,0,0

After this point, when I try to use, previewView.bounds property, it returns me its original size as 0.

How can I get the bounds as it shows on the screen with the related constaints' setup ?

Thank you very much Guys.

Upvotes: 3

Views: 4108

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can access it in

 override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if once { 
        once = false
        // process here
        print(previewView.bounds) 
    } 
 }

but first declare the view as instance variable , make once = false in view

var previewView:UIView! 
var once= true

see hereenter image description here

Upvotes: 5

Related Questions