UIView 不改变旋转时的宽度和高度

UIView not changing the width and height on Rotate

当我将设备从纵向旋转到横向时,我的问题就出在这里,我的自定义 uiview 没有改变它们的宽度和高度。因此,当设备处于横向状态时,它仍会获得纵向设备的宽度和高度。到目前为止,这是我的代码:

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)
    }

}

你应该根据情况设置框架。试试这个:

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

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

}

您甚至没有更改视图的高度和宽度,将以下代码添加到您的 orientationChanged() 以了解设备的当前方向并调整其大小。

func orientationChanged() {

    // Consider using UIScreen.mainScreen().bounds.width and height in CGRect   
    if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
    {
        print("landscape")
        centerView.frame = // CGRect for landscape
    }

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
    {
        print("Portrait")
        centerView.frame = //CGRect for portrait
    }

}

您需要调整 basicView class 视图的大小,而不仅仅是子视图。

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

另外,您需要检查当前设备方向并根据方向设置框架

func orientationChanged() {
    if(isLandscape) {}
    else {}
}