2

I would like a smooth animation of this view whenever the search bar is selected and deselected. 现在它是波涛汹涌的:

在此处输入图像描述

下面是我在 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)
    }
}

任何帮助表示赞赏,谢谢!

4

1 回答 1

1

我找到了解决方案。最初我在 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 时它不起作用,请随时告诉我。谢谢!

于 2022-02-01T20:24:47.867 回答