Swift viewWillTransition not called

后端 未结 4 884
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 16:27

I\'m creating a full screen image gallery using a UICollectionView. When the user rotates the device, I perform updates to the UICollectionView wit

4条回答
  •  情话喂你
    2020-12-20 17:05

    If you are just concern about the layout when the device rotate then please use:

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
        collectionView.collectionViewLayout.invalidateLayout()
        collectionView.layoutIfNeeded()
    }
    

    From apple docs:

    public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
    

    This method is called when the view controller's view's size is changed by its parent (i.e. for the root view controller when its window rotates or is resized). If you override this method, you should either call super to propagate the change to children or manually forward the change to children.

    I guess you might called this function on a parent of that view without calling super

    A work around would also be to register for the device rotation:

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    
        NotificationCenter.default.removeObserver(self)
    }
    
    func deviceOrientationDidChange(_ notification: Notification) {
        let orientation = UIDevice.current.orientation
        print(orientation)
    }
    

提交回复
热议问题