我应该使用哪个动画师来交换UILabel.text值?

时间:2019-03-06 03:30:30

标签: swift animation

我正在尝试只交换两个不同UILabel的UILabel文本值。 我现在用UIView.animate(withDuration:0.5)来做,但是似乎根本没有动画。

enter image description here

这是我当前的代码

@IBOutlet weak var nameLabel1: UILabel!
@IBOutlet weak var nameLabel2: UILabel!
@IBOutlet weak var positionLabel1: UILabel!
@IBOutlet weak var positionLabel2: UILabel!
@IBOutlet weak var emailLabel1: UILabel!
@IBOutlet weak var emailLabel2: UILabel!


struct Person{
    var name: String?
    var position: String?
    var email: String?
}


@IBAction func clickMe2Tapped(_ sender: Any) {
    print("first click me tapped")
    var tempPerson = Person()
    tempPerson.name = nameLabel1.text
    tempPerson.position = positionLabel1.text
    tempPerson.email = emailLabel1.text

    UIView.animate(withDuration: 0.5) {
        self.nameLabel1.text = self.nameLabel2.text
        self.positionLabel1.text = self.positionLabel2.text
        self.emailLabel1.text  = self.emailLabel2.text

        self.nameLabel2.text = tempPerson.name
        self.positionLabel2.text = tempPerson.position
        self.emailLabel2.text = tempPerson.email
    }
}

1 个答案:

答案 0 :(得分:1)

有很多方法可以实现目标。以下是其中之一。

    @IBAction func clickMe2Tapped(_ sender: Any) {
    print("first click me tapped")

    //swap data
    var tempPerson = Person()
    tempPerson.name = nameLabel1.text
    tempPerson.position = positionLabel1.text
    tempPerson.email = emailLabel1.text


    self.nameLabel1.text = self.nameLabel2.text
    self.positionLabel1.text = self.positionLabel2.text
    self.emailLabel1.text  = self.emailLabel2.text

    self.nameLabel2.text = tempPerson.name
    self.positionLabel2.text = tempPerson.position
    self.emailLabel2.text = tempPerson.email

    //Add animation
    let transition = CATransition.init()
    transition.type = .moveIn
    transition.timingFunction = CAMediaTimingFunction(name: .easeOut)
    transition.subtype = CATransitionSubtype.fromBottom
    transition.duration = 0.5
      self.nameLabel1.layer.add(transition, forKey: nil)
      self.positionLabel1.layer.add(transition, forKey: nil)
      self.emailLabel1.layer.add(transition, forKey: nil)
      self.nameLabel2.layer.add(transition, forKey: nil)
      self.positionLabel2.layer.add(transition, forKey: nil)
      self.emailLabel2.layer.add(transition, forKey: nil)

 }