2017-12-01 15 views
0

UICollectionViewCellsが表示された後に3秒間フェードしたい、または潜在期のメッセージを消滅させる方法のように8秒間フェードさせたい。ここに私のコードの関連部分です:指定された時間後にUICollectionViewCellをフェードアウトする方法

override func cellForItem(at index: Int) -> UICollectionViewCell { 
    // ... 

    // Get the time interval since the message was posted 
    let timeInterval = 11 - Date().timeIntervalSince(message.timestamp) 

    // If within the last 3 seconds, begin a fade. 
    if timeInterval <= 3, timeInterval > 0 { 
     cell.alpha = CGFloat(1 - 3/timeInterval) 
     cell.fadeAlpha(to: 0, duration: timeInterval) { finished in 
      if finished { 
       self.delegate?.removeMessage(withSectionController: self) 
      } 
     } 
    } else if timeInterval <= 0 { 
     // If 11 secs or more have passed, remove. 
     self.delegate?.removeMessage(...) 
     cell.alpha = 0 
    } else { 
     // Otherwise start a timer 
     timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(removeMessage), userInfo: nil, repeats: false) 
    } 
    return cell 
} 


@objc private func removeMessage() { 
    timer.invalidate() 
    // In other code I have got the cell 
    // This is a UIView animation that changes the alpha 
    cell.fadeAlpha(to: 0, duration: 3) { finished in 
     if finished { 
      self.delegate?.removeMessage(...) 
     } else { 
      // This gets cancelled on other cells when removeMessage gets called on a cell. 
     } 
    } 
} 


// In the delegate 
func removeMessage(...) { 
    model.messages.removeFirst() 
    // This performs updates on the collection view data 
    performUpdates() 
} 

...は、他のコードが、その関係ありませんがあることを意味します。

自分のコレクションビューがセルを更新する場合を除いて、自分のコードは機能しますが、現在のフェードはキャンセルされます。これをどうすれば解決できますか?

+0

セルが既にフェードの途中にある場合、セル「アルファ」を設定しないでください。 – matt

+0

@mattセルがリロードされた場合、セルの最初のアルファを設定し、そこからフェードを続けると考えました – Tometoyou

答えて

0

これをカスタムUICollectionViewLayoutとして実装する必要があります。表示した後、あなたのモデルからのメッセージを削除し、あなたがフェードアウトしたい項目のためのあなたのコレクションビューに

deleteItems(at: [IndexPath]) 

を呼び出すことによって、セルを削除するようにタイマーを設定します。

あなたはこの方法では、に をアニメ化される属性を指定

finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? 

を実装しているしたいと0 ​​

alphaプロパティを設定してUICollectionViewLayoutAttributesインスタンスを返しますカスタムレイアウトで

コレクションビューからアイテムを削除するときに使用します。

+0

3秒間にアルファ0にフェードするように設定するにはどうすればよいですか? – Tometoyou

+0

ああ、そうだ。私が知っている限り、それは実際には簡単に利用できません。カスタム期間を達成できるいくつかのソリューションについては、この質問をhttps://stackoverflow.com/questions/12922780/how-do-you-set-the-duration-for-uicollectionview-animationsでチェックしてください。 –

関連する問題