簡體   English   中英

iOS在應用啟動時為子視圖設置動畫嗎?

[英]IOS animating subviews as app launches?

我只是想在某些uiview中制作動畫,

  • 首先,我將子視圖從viewWillAppear的屏幕范圍中刪除
  • 然后我使用viewDidAppear UIView.animate將它們移回原位

`

override func viewWillAppear(_ animated: Bool) {
  super.viewWillAppear(animated)
  label.center.x -= view.bounds.width
  username.center.x -= view.bounds.width
  password.center.x -= view.bounds.width
  login.center.x -= view.bounds.width
}

override func viewDidAppear(_ animated: Bool) {
  super.viewDidAppear(animated)
  print("view did appear")
  UIView.animate(withDuration: 1) {
    self.label.center.x += self.view.bounds.width
    self.username.center.x += self.view.bounds.width
    self.password.center.x += self.view.bounds.width
    self.login.center.x += self.view.bounds.width
  }
}

我做錯了什么?

編輯1

當我評論任一viewDidAppear它對視圖均無影響。 (它們在情節提要中就位)

Aeid,我想提供一種替代解決方案,如果可能的話,允許您對是否有約束進行動畫處理。

分組

我注意到您正在移動4個UI元素。 我可能建議您將它們全部組合到一個UIView中(具有清晰的背景色)。 這樣,您只需要為一個UI元素設置動畫。 一個UIView

動畫

我最喜歡的動畫對象方法之一是“轉換”它。 您可以應用3種轉換:

  1. 回轉
  2. 調整大小(稱為“縮放”)
  3. 重新定位(稱為“翻譯”)

每個UI對象都有一個.transform屬性。 您可以使用CGAffineTransform應用轉換。 (CG =核心圖形,仿射=保留平行關系。旋轉,調整大小和重新放置不會使對象傾斜或扭曲)

class ViewController: UIViewController {

    @IBOutlet weak var loginView: UIView!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loginView.transform = CGAffineTransform(translationX: -view.bounds.width, y: 0)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        UIView.animate(withDuration: 1) {
            self.loginView.transform = .identity // Remove the transform
        }
    }
}

動畫登錄

好處

  • 對對象有什么約束都沒有關系。 它會工作。
  • 您不必重新放置兩次,只需一次。 然后刪除變換以使其返回其原始位置。

您需要在該動畫閉包內添加self.view.layoutIfNeeded()

UIView.animate(withDuration: 1) {
    self.label.center.x += self.view.bounds.width
    self.username.center.x += self.view.bounds.width
    self.password.center.x += self.view.bounds.width
    self.login.center.x += self.view.bounds.width

    self.view.layoutIfNeeded()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM