簡體   English   中英

使用 safeAreaLayoutGuide (Swift 5) 的動畫

[英]Animations with safeAreaLayoutGuide (Swift 5)

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

任何幫助表示贊賞,謝謝!

我找到了解決方案。 最初我在 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 時它不起作用,請隨時告訴我。 謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM