hide/show uiimageview 点击按钮时带有动画

hide/show uiimageview with animation when clicking button

我该如何实现,当我点击按钮时,我的图像会随着动画移出屏幕,而当我再次点击按钮时,又会回到原来的位置?

使用此代码向左移动-

func moveToLeft()
{
    var frame = imageView.frame
    frame.origin.x = -imageView.frame.size.width //Adjust this value according to your need
    UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: {() -> Void in
        self.imageView.frame = frame
    }, completion: {(_ finished: Bool) -> Void in
        /*done*/
    })
}

使用此代码向右移动-

func moveToRight()
{
    var frame = imageView.frame
    frame.origin.x = 0 //Adjust this value according to your need
    UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: {() -> Void in
        self.imageView.frame = frame
    }, completion: {(_ finished: Bool) -> Void in
        /*done*/
    })
}

button 单击事件上,根据您的要求简单地为 imageViewx coordinate of origin 设置动画。

示例:

@IBAction func onTapButton(_ sender: UIButton)
{
    if sender.isSelected
    {
        UIView.animate(withDuration: 2.0, animations: {
            self.imageView.frame.origin.x = 0.0
        })
    }
    else
    {
        UIView.animate(withDuration: 2.0, animations: {
            self.imageView.frame.origin.x = UIScreen.main.bounds.width
        })
    }
    sender.isSelected = !sender.isSelected
}

以上代码将按如下方式工作:

  1. selectingbutton时,imageView'sx coordinate of origin移动到屏幕的extreme right(UIScreen.main.bounds.width)

  2. de-selectingbutton,imageView'sx coordinate of origin移动到屏幕的extreme left时(0.0)