Home > Software design >  Hide view in iOS and rearrange other view with fullscreen
Hide view in iOS and rearrange other view with fullscreen

Time:06-02

Let's assume I have this layout design on an iPhone Portrait. A Label (red) and an Image (blue).

enter image description here

But I would like to have it this way when the iPhone is in landscape. Only the image (blue).

enter image description here

I trying with following code but the label does not appear after return back to portrait:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
 
    coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in

        let orient = UIDevice.current.orientation

        switch orient {
        case .portrait:
            print("Portrait")
            let ctop = NSLayoutConstraint(item: self.imageView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 44)
            self.view.removeConstraint(ctop)
            self.labelView.isHidden = false
            break
        default:
            print("LandScape")
            let ctop = NSLayoutConstraint(item: self.imageView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 0)
            self.view.addConstraint(ctop)
            self.labelView.isHidden = true
            break
        }
        }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
            print("rotation completed")
    })
}

CodePudding user response:

You have a mixup with your addConstraint/removeConstraint logic. In the Portrait case you define a new cTop constraint and remove it (!?!) from the view - you probably want to add it.

It would be better to define both constraints right away when you create your views, and only set one to active - and then switch the isActive setting on both according to your new orientation. Or only define one constraint and just change the constant on it accordingly.

  • Related