首页 > 解决方案 > 用动画水平移动 UIImage

问题描述

我想UIImageView从左到右和从右到左水平移动。我设计如下。

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

编辑 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
            }
        }
}

要求

默认看起来像这样。 在此处输入图像描述

当用户按下按钮时,动画完成后将如下所示。

在此处输入图像描述

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

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

我怎样才能做到这一点。你能帮帮我吗?谢谢

标签: iosswiftanimation

解决方案


您需要将wrt 的动画设置frame为(绿色视图),即arrowImageViewcustomView

@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状态,sender

@IBAction func onTapButton(_ sender: UIButton) {
    sender.isSelected = !sender.isSelected //here...
    //rest of the code...
}

在此处输入图像描述


推荐阅读