【问题标题】:UIView not changing the width and height on RotateUIView 不会改变 Rotate 的宽度和高度
【发布时间】:2016-03-16 04:05:51
【问题描述】:

当我将设备从纵向旋转到横向时,我的问题就在这里,我的自定义 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)
    }

}

【问题讨论】:

    标签: ios swift uiview uiinterfaceorientation


    【解决方案1】:

    您应该根据条件设置框架。试试这个:

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

    【讨论】:

      【解决方案2】:

      您甚至没有更改视图的高度和宽度,请将以下代码添加到您的 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
          }
      
      }
      

      【讨论】:

        【解决方案3】:

        你需要调整 basicView 类的视图而不是它的子视图。

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-02
          • 2017-05-26
          • 2016-04-02
          • 1970-01-01
          相关资源
          最近更新 更多