当我更改设备的方向时,为什么框架中的值大于等于特定大小的值不能执行相同的工作?

时间:2019-05-14 13:25:26

标签: ios swift uiview uiviewcontroller uiimageview

我有一段代码,可以让我在更改设备方向时更改async的大小。

我对该值进行了硬编码(高度= 896,宽度= 414),并且效果很好,但是当我想通过放置动态值(UIImageViewheight = self.view.frame.size.height)来生成动态尺寸时,它不起作用...

但是,width = self.view.frame.size.width = 896和self.view.frame.size.height = 414,这很奇怪……我错过了我的想法。

self.view.frame.size.width

编辑(解决方案): 对于信息,我使用了这种方式编写代码,但是故障单中的解决方案更短,更现代

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
        self.newImageView?.frame.size.height = 414
        self.newImageView?.frame.size.width = 896
        navBar?.frame = CGRect(x: 0, y: 0, width: 896, height: 100)
    } else {
        print("Portrait")
        self.newImageView?.frame.size.height = 896
        self.newImageView?.frame.size.width = 414
        navBar?.frame = CGRect(x: 0, y: 40, width: 414, height: 100)
    }
}  

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

在该方法中放置一个断点,您将看到在视图改变方向之前调用了此方法,这就是为什么您没有适当的高度和宽度,而是使用size参数中的值,这应该起作用的原因

但是同意评论,而是使用自动布局,这将使您的生活更轻松

答案 1 :(得分:1)

如果您要调整导航栏的大小

 self.navBar.autoresizingMask = (UIView.AutoresizingMask(rawValue: UIView.AutoresizingMask.RawValue(UInt8(UIView.AutoresizingMask.flexibleRightMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleLeftMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleBottomMargin.rawValue) | UInt8(UIView.AutoresizingMask.flexibleTopMargin.rawValue))))

将其放在您的view.addSubview(navBar!)

之后