Hieu Duc Pham
Hieu Duc Pham

Reputation: 1074

How to setup a view with a half of screen height?

I want to set view1's height to half of the screen's height for all devices (when the device in the portrait mode)

Here is what I want it to look like:

enter image description here

so I make an auto layout of View1's height

    @IBOutlet weak var heighConstraint: NSLayoutConstraint!

my viewwillappear function here:

override func viewWillAppear(animated: Bool) {
        self. heighConstraint.constant = self.view.frame.size.height / 2
}

But it's not worked when I ran my app. what's wrong in here?

Upvotes: 9

Views: 10185

Answers (3)

Jen Jose
Jen Jose

Reputation: 4035

I know the accepted answer is correct but there is simpler method to do so -

Add the view (the one shown in yellow color). Pin it to three edges (top, leading and trailing). I have set it as 0 but change it as per your need.

enter image description here

Create Height Equal to constraint to main View as

enter image description here

enter image description here

Open that Constraint in the Inspector view and edit the multiplier as 0.5. Setting it as 0.5 takes the height value of half the height of mainView.

enter image description here

Just make sure FirstItem = View1 and SecondItem = SuperView as shown in the image.

Upvotes: 31

IRAVIPATEL
IRAVIPATEL

Reputation: 71

Please try this out. Hope it will help you out. The below line will take the bounds of the device and will set the frame or height according to it.

view1.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height/2);

Hope this helps!!! Good Luck...

Upvotes: 0

tounaobun
tounaobun

Reputation: 14857

Try to change heightConstraint's constant value in viewDidLayoutSubviews method.

override func viewDidLayoutSubviews() {
    heightConstraint.constant = self.view.frame.size.height / 2
}

Upvotes: 13

Related Questions