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

标签 ios swift uiview uiinterfaceorientation

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

}

关于ios - UIView 不改变旋转时的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36026602/

相关文章:

ios - 如何使所有设备上的动画 View 与屏幕底部的距离保持一致?

ios - Swift:为什么在 touchesBegan() 中将 UIView 的帧大小引用为 (0.0, 0.0)?

ios - 根据按下的按钮,通过 Segue 传递变量返回的对象

ios - 为数组中的每个字符串获取 firebase 数据

ios - 在主视图层上方添加 subview

ios - 如何修复 Twilio 可编程语音错误 - 52134 无效的 APNs 设备 token

ios - 可选类型 String 的值必须解包为 String 的值类型?

iphone - 如果drawRect : is overridden,子类UIView显示黑色背景

ios - 将视点转换为 MKMapView 坐标

iphone - 在被遮挡时激活接近监控以关闭 iPhone 屏幕