Swift - How to detect orientation changes

后端 未结 13 1795
余生分开走
余生分开走 2020-11-29 19:49

I want to add two images to single image view (i.e for landscape one image and for portrait another image)but i don\'t know how to detect orientation changes using swift lan

13条回答
  •  一整个雨季
    2020-11-29 20:53

    Swift 4

    I've had some minor issues when updating the ViewControllers view using UIDevice.current.orientation, such as updating constraints of tableview cells during rotation or animation of subviews.

    Instead of the above methods I am currently comparing the transition size to the view controllers view size. This seems like the proper way to go since one has access to both at this point in code:

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        print("Will Transition to size \(size) from super view size \(self.view.frame.size)")
    
        if (size.width > self.view.frame.size.width) {
            print("Landscape")
        } else {
            print("Portrait")
        }
    
        if (size.width != self.view.frame.size.width) {
            // Reload TableView to update cell's constraints.
        // Ensuring no dequeued cells have old constraints.
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    
    
    }
    

    Output on a iPhone 6:

    Will Transition to size (667.0, 375.0) from super view size (375.0, 667.0) 
    Will Transition to size (375.0, 667.0) from super view size (667.0, 375.0)
    

提交回复
热议问题