使用动画水平移动UIImage

时间:2020-08-31 05:15:59

标签: ios swift animation

我想从左向右和从右向左水平移动UIImageView。 我对此进行了如下设计。

  1. UIView(绿色)
  2. 箭头图像(UIView的引线,UIView的垂直居中,固定高度,宽度)
  3. UILabel(UIView的水平居中和垂直居中)
  4. 按钮(UIView的顶部,顶部,底部,底部) 在上图中,绿色是UIView,左箭头图标是image。因此,当用户按下按钮时,我想将箭头图像从从左移到右,从从右移到左,反之亦然。

编辑1

感谢您的回答

if sender.isSelected {
    UIView.animate(withDuration: 1.0, animations: {
        self.imgVWInOut.frame.origin.x = (self.vwPunchInOut.bounds.maxX - self.imgVWInOut.bounds.width) - 10
        }) { (done) in
    }
 } else {
     UIView.animate(withDuration: 1.0, animations: {
         self.imgVWInOut.frame.origin.x = 10
         }) { (done) in
      }
 }

但是当我尝试更改UIView背景颜色和UIImageView图像时,动画无法正常工作。

@IBAction func btnPunchInOutTapped(_ sender: UIButton) {
    sender.isSelected = !sender.isSelected
    if sender.isSelected {
            UIView.animate(withDuration: 1.0, animations: {
                self.imgVWInOut.frame.origin.x = (self.vwPunchInOut.bounds.maxX - self.imgVWInOut.bounds.width) - 10
            }) { (done) in
                self.imgVWInOut.image = #imageLiteral(resourceName: "ic_punchout")
                self.lblPunchInOut.text = "Punch out".localized()
                self.vwPunchInOut.backgroundColor = Colors.punchOutColor
            }
        } else {
            UIView.animate(withDuration: 1.0, animations: {
                self.imgVWInOut.frame.origin.x = 10
            }) { (done) in
                self.imgVWInOut.image = #imageLiteral(resourceName: "ic_punchout")
                self.lblPunchInOut.text = "Punch out".localized()
                self.vwPunchInOut.backgroundColor = Colors.punchOutColor
            }
        }
}

要求

默认外观如下所示。 enter image description here

用户按下按钮后,动画制作完成后将显示以下外观。

enter image description here

GIF链接:https://drive.google.com/file/d/1R2hfcwfhyO5JA9CQt1_6Auto3YBRj3yn/view?usp=sharing

演示项目链接:https://drive.google.com/file/d/1H0b3D61fPIxWqSZL8tdvp0RP8juVdr_Z/view?usp=sharing

我该如何做到这一点。你能帮我吗 谢谢

1 个答案:

答案 0 :(得分:1)

您需要将frame中的arrowImageView设置为customView(绿色视图)的动画,即

@IBAction func onTapButton(_ sender: UIButton) {
    self.arrowImageView.frame.origin.x = self.customView.bounds.minX
    UIView.animate(withDuration: 1.0) {
        self.arrowImageView.frame.origin.x = self.customView.bounds.maxX - self.arrowImageView.bounds.width
    }
}

根据您的要求提供动画duration

编辑:

您需要在点击按钮时更改isSelected的{​​{1}}状态,

sender

enter image description here