簡體   English   中英

animateWithDuration沒有顯示

[英]animateWithDuration is not showing

我正在學習Swift,但在將UIView從不同的功能移到我遇到了問題。 如果我使用這個:

ViewController:

let boardView = BoardView()

@IBAction func startButtonTapped(sender: UIButton) {
    view.addSubview(boardView.background)
}

類BoardView:

class BoardView : UIView {

   let multiplier: CGFloat = 0.95
   let screenSize = UIScreen.mainScreen().bounds

   var background: UIView {
      let boardSize: CGFloat = multiplier * screenSize.width
      let board = UIView(
         frame: CGRectMake(-boardSize,
         screenSize.height / 2 - boardSize / 2,
         boardSize,
         boardSize)
      )

       board.layer.cornerRadius = 8.0
       board.backgroundColor = UIColor.blackColor()
       UIView.animateWithDuration(0.15, animations: {
          board.center.x = self.screenSize.width / 2
      })
      return board
   }
}

動畫有效(對我而言是違反直覺的)。 如果我嘗試將UIView從另一個函數中移出,如下所示:

ViewController按鈕:

@IBAction func startButtonTapped(sender: UIButton) {
    view.addSubview(boardView.background)
    boardView.moveBackground()
}

BoardView:

class BoardView : UIView {

let multiplier: CGFloat = 0.95
let screenSize = UIScreen.mainScreen().bounds

var background: UIView {
    let boardSize: CGFloat = multiplier * screenSize.width
    let board = UIView(
        frame: CGRectMake(-boardSize,
        screenSize.height / 2 - boardSize / 2,
        boardSize,
        boardSize))

    board.layer.cornerRadius = 8.0
    board.backgroundColor = UIColor.blackColor()
    return board
}

func moveBackground() {
    UIView.animateWithDuration(0.15, animations: {
        self.background.center.x = self.screenSize.width / 2
    })
 }
}

動畫無效。 如果我在ViewController中使用animateWithDuration也沒有任何animateWithDuration

如何將UIView從創建位置移動到另一個位置?

您的原始代碼雖然工作異常,但實際上定義不正確。 在將視圖添加到視圖層次結構之前,不應開始對其進行動畫處理。 您正在擺脫它,但不要那樣做。

在您更接近正確的第二種方法中,問題在於您已將background設為非惰性計算屬性。 因此,每次調用model.background ,都會得到一個不同的對象。

考慮到您是如何編寫的,背景的lazy屬性可能就是您真正的意思。

就像@dasdom指出的那樣, BoardModel對於視圖BoardModel是一個非常不好的名字。 這應該是BoardView

通常,您的流程有點奇怪。 我可能BoardView為其本身添加背景。 如果控制器實際上是將背景添加到其他視圖(而不是BoardView ),那么這確實很奇怪,您需要重新考慮代碼結構。

每當您訪問boardModelbackground (對於視圖來說這真是個壞名字!)時,都會創建並返回一個新視圖。 我認為這不是您想要的。

暫無
暫無

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

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