Komal Kamble
Komal Kamble

Reputation: 422

get Height Value from NSLayoutConstraint

In my project I am using AutoLayOut, There is one UIView which is subView main View, I have set its width(using constrains) equal to 2 :3 superView's width and its height equal to its View. I need view to be circular shape so I am setting its cornerRadius to heightOfView/2. There is 1:1 aspect ration of views's height and width. I have created Outlet of that constrain as

 @IBOutlet weak var circleHeight: NSLayoutConstraint

Now I want to acces its Height or Width but I m not gwtting actual value,

circleHeight.firstItem.frame.width

I am getting value which I have stored from Storyboard, There Is something I am Missing but could not figured it out

enter image description here Selected View should be circular. but when i print its constain's values it gives height and width as 214 only

Upvotes: 0

Views: 1492

Answers (3)

Rohit Pradhan
Rohit Pradhan

Reputation: 3875

  1. I think you might be fetching value in viewWillAppear or ViewDidLoad but views frames don't get updated when these method gets called
  2. So you need to fetch the width or height in ViewDidAppear method.
  3. If get the height or width in ViewDidLayoutSubViews, performance gets degraded as it gets called many times.

Here is Code

override func viewDidAppear(animated: Bool){
       super.viewDidAppear(animated)
       let viewHeight = CGRectGetHeight(yourView.frame)
       yourView.layer.cornerRadius = viewHeight / 2
       yourView.layer.masksToBounds = true
    }

Upvotes: 0

ruslan.musagitov
ruslan.musagitov

Reputation: 2124

You can create IBOutlet for this UIView, which should be circle shape. Then in viewDidLayoutSubviews() method you can read its height and make it circle:

override func viewDidLayoutSubviews() {
    let viewHeight = CGRectGetHeight(yourView.frame)
    yourView.layer.cornerRadius = viewHeight / 2
    yourView.layer.masksToBounds = true
}

Upvotes: 1

jandro_es
jandro_es

Reputation: 44

A constraint does not have height or width, only relationships, priorities and constant values, depending in how you set the constraint itself.

To access the height of the subview you are interested in, you need to access as always:

<uiview_outlet>.frame.size.height

Hope it helps.

Upvotes: 0

Related Questions