使用 safeAreaLayoutGuide 的动画 (Swift 5)

Animations with safeAreaLayoutGuide (Swift 5)

无论何时选择和取消选择搜索栏,我都希望此视图有一个流畅的动画。现在起伏不定:

下面是我在 searchResultsUpdater 中的代码。据我了解,这些函数应该处理动画,我不确定这里出了什么问题:

func updateSearchResults(for searchController: UISearchController) {
    
    //MapView moves up when search bar is selected
    if searchController.isActive == true{
        UIView.animateKeyframes(withDuration: 0.25, delay: 0.0, options: UIView.KeyframeAnimationOptions(rawValue: 7), animations: {
            self.mapView.frame.origin.y=self.view.safeAreaLayoutGuide.layoutFrame.origin.y

        },completion: nil)
    }
    
    //MapView moves down when cancel button is selected
    if searchController.isActive == false{
        UIView.animateKeyframes(withDuration: 0.25, delay: 0.0, options: UIView.KeyframeAnimationOptions(rawValue: 7), animations: {
            self.mapView.frame.origin.y=self.view.safeAreaLayoutGuide.layoutFrame.origin.y
            
        },completion: nil)
    }
}

感谢任何帮助,谢谢!

我找到了解决办法。最初我在 viewDidLayoutSubviews():

中有 mapView 框架的 CGRect
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
     //layout to fit frame of view
    mapView.frame = CGRect(x: 0, y: view.safeAreaInsets.top, width: 
    view.frame.size.width, height: view.frame.size.height - 
    view.safeAreaInsets.top)
  
}

我把它移到了 viewDidLoad() 中,现在它可以工作了:

override func viewDidLoad() {
    super.viewDidLoad()
    
    //add gesture recognizer for mapView
    mapView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(mapViewAnimation)))
    //layout to fit frame of view
    mapView.frame = CGRect(x: 0, y: view.safeAreaInsets.top, width: 
    view.frame.size.width, height: view.frame.size.height - 
    view.safeAreaInsets.top)

}

我还添加了一个手势识别器,这样 searchResultsUpdater 就不会那么混乱了:

//handle the animation for mapview
@objc func mapViewAnimation(){
    UIView.animateKeyframes(withDuration: 0.25, delay: 0.0, options: 
    UIView.KeyframeAnimationOptions(rawValue: 7), animations: {
        
    self.mapView.frame.origin.y = 
    self.view.safeAreaLayoutGuide.layoutFrame.origin.y
        
    },completion: nil)
    
}

如果有人知道为什么当我在 didLayoutSubViews() 中使用 CGRect 时它不起作用,请随时告诉我。谢谢!