簡體   English   中英

使圖像從屏幕左右移動

[英]Making Images move left to right out of the screen

我試圖使我的頂部和底部圖像移出屏幕,以及當它們移出屏幕時; 我的圖像徽標出現。 這很正常,但是當我限制我的圖像時,他們做的卻相反。

因此,它們不是移出屏幕,而是從屏幕外部進入屏幕。

這是我的代碼,在此先感謝。

func dismissImages(){
        imageLogo.isHidden = true

        UIView.animate(withDuration: 17) {
            //self.topImage.frame.origin.x
            self.topImage.center.x -= 400

        }


        UIView.animate(withDuration: 17, animations: {
            self.bottomImage.center.x += 400
        }) { (sucess) in
            if sucess {
                self.imageLogo.isHidden = false
            }
        }

我建議設置動畫層而不是視圖本身

func dismissImages(){
    imageLogo.isHidden = true

    UIView.animate(withDuration: 17) {
        self.topImage.layer.frame.origin.x -= self.view.frame.width
    }

    UIView.animate(withDuration: 17, animations: {
        self.bottomImage.layer.frame.origin.x += self.view.frame.width
    }) { guard $0 else { return }
        self.imageLogo.isHidden = false
    }
}

為每個圖像設置一個NSLayoutConstraint並為該約束設置動畫。

// SETUP INITIAL POSITION
let topImageHorizontalConstraint = NSLayoutConstraint(item: topImage, attribute: NSLayoutAttribute.centerX, relatedBy: .equal, toItem: parentView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0) // Note: Change the constant from 0 to whatever you need it to be initially.

// ACTIVATE CONSTRAINT
topImageHorizontalConstraint.isActive = true

// ANIMATE THE CONSTANT ON THE CONSTRAINT
// Note: This part will be in dismissImages().
UIView.animate(withDuration: 17, animations: {
    topImageHorizontalConstraint.constant -= 400                
},
completion: { (animationFinished: Bool) in
    if animationFinished {
            // Show logo or whatever
    }
})

從iOS 9+開始,您可以使用NSLayoutAnchor創建約束並稍微簡化一下事情。

// SETUP INITIAL POSITION
let topImageHorizontalConstraint = topImage.centerXAnchor.constraint(equalTo: parentView.centerXAnchor, constant: 0)

// ACTIVATE CONSTRAINT
topImageHorizontalConstraint.isActive = true

// ANIMATE THE CONSTANT ON THE CONSTRAINT
// Note: This part will be in dismissImages().
UIView.animate(withDuration: 17, animations: {
    topImageHorizontalConstraint.constant -= 400                
},
completion: { (animationFinished: Bool) in
    if animationFinished {
            // Show logo or whatever
    }
})

我喜歡錨點,因為看起來關系很容易,但是在這種情況下卻非常相似。

注意:您需要在dismissImages()之外具有用於約束的變量。 然后在init()或viewDidLoad()或最初的某個地方創建約束,然后調用dismissImages()對更改進行動畫處理。

我想到了。 在調用約束函數之前,我先調用了動畫函數。 當我在ViewDidAppear中添加mu動畫功能時,我的工作非常完美。 這樣,僅當視圖出現並且設置了約束時,動畫才會發生。

謝謝。

暫無
暫無

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

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