首页 > 解决方案 > 当我更改设备的方向时,为什么框架中的值比等于特定大小不做同样的工作?

问题描述

我有一段代码允许我在更改UIImageView设备方向期间更改 an 的大小。

height = self.view.frame.size.height我硬编码了这个值(高度 = 896 和宽度 = 414),它工作得很好,但是当我想通过放置动态值(和)来做一个动态大小时width = self.view.frame.size.width,它不起作用......

但是,self.view.frame.size.height= 896 和self.view.frame.size.width= 414 这很奇怪......我错过了一些我认为的东西。

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

编辑(解决方案):对于信息,我在代码中使用了这种方式,但票证中的解决方案更短,更现代

 //Share bar
        let shareBar: UIBarButtonItem = UIBarButtonItem.init(barButtonSystemItem:.action, target: self, action: #selector(userDidTapShare))
        self.navigationItem.rightBarButtonItem = shareBar
        if UIDevice.current.orientation.isLandscape {
            let width =  max(self.view.frame.size.width, self.view.frame.size.height)
            let height = min(self.view.frame.size.width, self.view.frame.size.height)
            self.newImageView?.frame.size.height = height
            self.newImageView?.frame.size.width = width
            navBar = UINavigationBar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.height, width: width, height: 100))
        } else {
            let width =  min(self.view.frame.size.width, self.view.frame.size.height)
            let height = max(self.view.frame.size.width, self.view.frame.size.height)
            self.newImageView?.frame.size.height = height
            self.newImageView?.frame.size.width = width
            navBar = UINavigationBar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.height, width: width, height: 100))
        }
        view.addSubview(navBar!)

有任何想法吗?

标签: iosswiftuiviewuiviewcontrolleruiimageview

解决方案


如果要调整导航栏的大小

 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!) 之后


推荐阅读