制作一个滑动动画和 hide/show 一个 UIView(swift 5)

Making an animation to slide and hide/show an UIView(swift 5)

我想为这两个视图添加动画。

  1. 红色UIView
  2. 绿色UIView

My storyboard look like this

从图中我想在点击这两个视图时添加一个动画。

首先从隐藏红色开始UIView

操作:1

when i click on green view i want green uiview silde to the right side until it disappear

红色的UIView会立即从右侧滑出

red uiview slide from right side

并在情节提要中的那个点停止并隐藏绿色 UIView

操作:2

当我点击红色视图时,我想让它向右滑动直到它消失。显示绿色 UIView 也从右上角出来,隐藏红色 UIView.

red UIView slide out

我的代码

import UIKit

class TestViewCell: UICollectionViewCell {

    @IBOutlet weak var bgView: UIView!

    @IBOutlet weak var bgAlertView: UIView!
    @IBOutlet weak var imgAlert: UIImageView!

    @IBOutlet weak var bgAlreadyAlertView: UIView!
    @IBOutlet weak var imgAlreadyAlert: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()

        //Make an action when tap on bgAlertView
        let actionBgAlert : Selector = #selector(self.actionBgAlert)
        let viewPostsViewGesture = UITapGestureRecognizer(target: self, action: actionBgAlert)
        bgAlertView.isUserInteractionEnabled = true
        bgAlertView.addGestureRecognizer(viewPostsViewGesture)

        //Make an action when tap on bgAlreadyAlertView
        let actionBgAlreadyAlert : Selector = #selector(self.actionBgAlreadyAlert)
        let viewAlreadyViewGesture = UITapGestureRecognizer(target: self, action: actionBgAlreadyAlert)
        bgAlreadyAlertView.isUserInteractionEnabled = true
        bgAlreadyAlertView.addGestureRecognizer(viewAlreadyViewGesture)

    }

    //action1
    @objc func actionBgAlert(sender: UITapGestureRecognizer){

        if imgAlert.image == #imageLiteral(resourceName: "alarm") {

            self.bgAlertView.isHidden = true
            self.bgAlreadyAlertView.isHidden = false 

    }

    //action2
    @objc func actionBgAlreadyAlert(sender: UITapGestureRecognizer){

        if imgAlreadyAlert.image == #imageLiteral(resourceName: "alarmedMain") {

            self.bgAlertView.isHidden = false
            self.bgAlreadyAlertView.isHidden = true 

    }

}

在情节提要中设置视图大小的限制。从它们共享的父视图右侧的红色视图和绿色视图的右侧设置约束。为两个视图的两个位置所需的值定义一些常量。 然后是这样的:

    @IBOutlet weak var greenConstraint : NSLayoutConstraint
    @IBOutlet weak var redConstraint : NSLayoutConstraint

    let greenSlideOutValue = -2000.0 // big enough to get green view offscreen
    let redSlideInValue = 0.0 // aligns red view right edge to superview

    let greenSlideInValue = 100.0 // puts green view onscreen offset from right edge
    let redSlideOutValue = -2500.0 // big enough to get red view offscreen.

    UIView.animate(withDuration: 0.75, delay: 1.0, options: .curveEaseOut, animations: {
          greenConstraint.constant = greenSlideOutValue
          redConstraint.constant = redSlideInValue
          self.view.layoutIfNeeded()
        }, completion: { finished in
          print(“slide green out, red in”)
        })

在事件处理程序中执行此操作,例如与视图关联的点击或手势识别器。对红色视图事件执行类似操作

代码未编译,只是输入,但应该可以帮助您入门。