bigpotato
bigpotato

Reputation: 27507

Swift + UIView: How to change y coordinates?

I have a UIView called descriptionView and I want to hide it initially when the screen first loads by offsetting the y coordinate to be the screen size + the height of descriptionView itself:

enter image description here

However, in my controller, none of my frame changes do anything:

  override func viewDidLoad() {
    super.viewDidLoad()
    ...
//    descriptionView.frame.origin.y =  self.view.frame.height
//    UIView.animateWithDuration(1, animations: {
//      self.descriptionView.frame.origin.y =  self.view.frame.height
//      self.view.layoutIfNeeded()
//    })
//    
    print("xxx")
    descriptionView.frame = CGRectMake(0, self.view.frame.height, self.view.frame.width, 66)
//    descriptionView.frame = CGRectOffset(descriptionView.frame, 0, descriptionView.frame.height)
  }

No matter what I do it seems fixed at that visible position like in my storyboard. Can someone help?

Upvotes: 0

Views: 5157

Answers (3)

Firo
Firo

Reputation: 15566

In IB you are using NSAutoLayout, so you either need to manipulate the constraints, or tell the view to translate the mask to constraints.

If you want to set the frame directly then you will want to do this:

descriptionView.translatesAutoresizingMaskIntoConstraints = true
descriptionView.frame = CGRectMake(...)

Otherwise you can create IBOutlets to the height and width constraint from IB and update those:

self.descriptionViewHeight.constant = self.view.frame.width

Additionally, I would recommend doing frame manipulations inside of viewWillAppear: rather than viewDidLoad. viewDidLoad does not strictly guarantee final position.

Upvotes: 2

shpasta
shpasta

Reputation: 1933

If you are using constraints, chaging the frame view myView.frame property will not affect on view actual position and size. Instead of this make constraint outlet and change it in your code, it will look like this:

descriptionView.heightConstraint.constant = 100

Also, if you want to hide something, you can use property myView.hidden = true, or myView.alpha = 0;

Upvotes: 1

Michaël Azevedo
Michaël Azevedo

Reputation: 3894

Instead of editing the frame or descriptionView, edit its height constraint.

First, create an NSLayoutConstraint from this constraint by cmd-dragging the height constraint from the Interface Builder to your class (like you do for any UI object).

Then you can set the constant property of this constraint to 0.


(Yes, constant is declared as a varproperty...)

Upvotes: 1

Related Questions