2017-05-27 72 views
1

我有一個x圖像列表。對於每一個圖像I創建的UIImageView與y中的視圖的高度和一個隨機X動畫滾動隨機延遲(一個接一個)和隨機水平位置的圖像

func computeImageFrame() -> CGRect { 
    let imageWidth: CGFloat = 91 
    let imageHeight: CGFloat = 131 

    var x = xPos() 
    let y = yPos() 

    if (x > ((self.backgroundView?.bounds.width)! - (self.backgroundView?.bounds.width)! * 0.20)){ 
     x = x.truncatingRemainder(dividingBy: ((self.backgroundView?.bounds.width)! - (self.backgroundView?.bounds.width)! * 0.20))} 

    return CGRect(x: x, y: y, width: imageWidth, height: imageHeight) 
} 

其中

func xPos() -> CGFloat { 
    return CGFloat(arc4random_uniform(UInt32((self.backgroundView?.frame.size.width)!))) 
} 
func yPos() -> CGFloat { 
    return self.backgroundView.bounds.height 
} 

在這一點上,我對的UIImageViews一個列表,其中x是隨機的,並且y是viewHeight和現在我想要進行動畫

func animateBackgroundFor(_ imageViews: [UIImageView]) { 
    for imageView in imageViews { 
     self.backgroundView.addSubview(imageView) 
    } 

    // Animate background 
    UIView.animate(withDuration: 6.0, delay: 0.0, options: [UIViewAnimationOptions.repeat, UIViewAnimationOptions.curveLinear], animations: { 
     for imageView in imageViews { 
      imageView.frame = imageView.frame.offsetBy(dx: 0.0, dy: -7 * imageView.frame.size.height) 
     } 
    }, completion: nil) 
} 

我的問題是我怎麼可以讓他們拍了一個又一個,而不是在同一時間,我怎麼能重新計算每個圖像的水平位置在不斷y循環。

謝謝

編輯:忘了提,我曾嘗試

func animateBackgroundFor(_ imageViews: [UIImageView]) { 
    for imageView in imageViews { 
     self.backgroundView.addSubview(imageView) 
    } 
    for imageView in imageViews { 
     UIView.animate(withDuration: 6.0, delay: 1.2, options: [UIViewAnimationOptions.repeat, UIViewAnimationOptions.curveLinear], animations: { 
      imageView.frame = imageView.frame.offsetBy(dx: 0.0, dy: -7 * imageView.frame.size.height) 
     }, completion: nil) 
    } 
} 

回答

2

請嘗試以下解決方案。 添加到您的控制器私有財產:

private var imageViews = [UIImageView]()

,然後修改您的animateBackgroundFor(_)方法以這樣的方式:

func animateBackgroundFor(_ imageViews: [UIImageView]) { 
    for imageView in imageViews { 
     self.backgroundView.addSubview(imageView) 
    } 
    self.imageViews = imageViews 
    animateImage(at: 0) 
} 

func animateImage(at index: NSInteger) { 
    guard index >= 0 && index < imageViews.count else { return } 
    let imageView = imageViews[index] 
    imageView.frame = computeImageFrame() 

    UIView.animate(withDuration: 6.0, 
        delay: 0.0, 
        options: UIViewAnimationOptions.curveLinear, 
        animations: { 
        imageView.frame = imageView.frame.offsetBy(dx: 0.0, dy: -7 * imageView.frame.size.height) 
    }, 
        completion: { 
     [weak self] finished in 
        guard finished && self != nil else { return } 
        let nextIndex = index + 1 < self!.imageViews.count ? index + 1 : 0 
        self!.animateImage(at: nextIndex) 
    }) 
} 
+0

偉大的作品!謝謝! –