Search code examples
iosswiftuiviewuiinterfaceorientation

UIView not changing the width and height on Rotate


my problem is here when I rotate the device from portrait to landscape my custom uiview doesn't change their width and height. So when the device is on landscape it still gets the width and the height of the device on portrait. So far this is my code:

import UIKit

class BasicView: UIView {

    let centerView: UIView = UIView()

    override init(frame: CGRect) {
        super.init(frame: frame)

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "orientationChanged", name: UIDeviceOrientationDidChangeNotification, object: nil)
        setupView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        print("orientation or other bounds-impacting change")
    }

    func orientationChanged() {
        centerView.frame = CGRectMake(0, 0,556.0,290.0);
    }

    func setupView() {
        centerView.frame = CGRectMake(0,0,self.frame.size.width,self.frame.size.height)
        self.addSubview(centerView)
    }

}

Solution

  • You should set the frame according to conditions. Try this:

    func orientationChanged()
    {
        if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
        {            
            print("landscape") // set frame for landscape
        }
    
        if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
        {
            print("Portrait") // set frame for portrait
        }
    
    }