簡體   English   中英

使用動畫將 UIView 移動或捕捉到屏幕的另一側

[英]Moving or snapping a UIView to other side of screen with animation

我正在使用Floaty Cocoapod為我的 iOS 應用程序制作一個浮動操作按鈕。 如果用戶希望將其移開,我希望能夠拖動此按鈕並將其對齊到屏幕的另一側。 Floaty cocoapod 已經提供了拖動它的方法,我正在嘗試修改此方法,以便按鈕將動畫捕捉到屏幕的對角(左下角)。 這是我到目前為止的地方:

extension UIView {

func addDragging(){
    
    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(draggedAction(_ :)))
    self.addGestureRecognizer(panGesture)
}

@objc private func draggedAction(_ pan:UIPanGestureRecognizer){
    
    let translation = pan.translation(in: self.superview)
    self.center = CGPoint(x: self.center.x + translation.x, y: self.center.y + translation.y)
    pan.setTranslation(CGPoint.zero, in: self.superview)
    

    // Added the following lines myself - not working

    if let superview = self.superview {
        if self.center.x < superview.frame.size.width / 2 {
            //self.transform = CGAffineTransform( translationX: 50, y: 0.0 )
        }
    }
}

}

我自己添加的代碼識別出按鈕已移至屏幕左側,但就我所知。 我只需要讓它在用戶停止拖動按鈕時將其自身設置為左下角,然后再將其向右移動到另一側。 我不確定我是否可以通過約束來做到這一點,因為我沒有使用故事板,也不知道這個 cocoapod 如何約束自己。 非常感謝任何幫助!

您可以通過將添加的代碼替換為以下內容來實現此目的:

if let superview = self.superview {
    // Case to move to the left
    if self.center.x < superview.frame.size.width / 2 {
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut) {
            self.frame = // Whatever your left frame is
        } completion: { (blockCalledAfterAnimationBool) in
            // A completion handler if you want it
        }
    } else { // Move to the right
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut) {
            self.frame = // Whatever your right frame is
        } completion: { (blockCalledAfterAnimationBool) in
            // A completion handler if you want it
        }
    }
}

重點是推薦使用UIView.animate()函數。 根據需要調整參數以獲得所需的動畫。

暫無
暫無

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

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