switchText.swift
extension UILabel {
/// テキストを切り替える。
///
/// - Parameters:
/// - texts: 表示したいテキストを指定
/// - intervalSec: 最初のフェードインが始まるまでの間隔秒数
/// - fadeinSec: フェードインにかかる秒数
/// - fadeoutSec: フェードアウトにかかる秒数
func switchLabel(texts: [String], intervalSec: TimeInterval, fadeinSec: TimeInterval, fadeoutSec: TimeInterval) {
var vIntervalSec = intervalSec
self.alpha = 0
self.text = texts[0]
texts.enumerated().forEach { index, text in
DispatchQueue.main.asyncAfter(deadline: .now() + vIntervalSec, execute: {[weak self] in
UIView.animate(
withDuration: fadeinSec,
animations: {
self?.alpha = 1
},
completion: { _ in
if texts.count - 1 > index {
UIView.animate(
withDuration: fadeoutSec,
animations: { self?.alpha = 0 },
completion: { _ in self?.text = texts[index + 1] })
}
}
)
})
vIntervalSec = vIntervalSec + fadeinSec + fadeoutSec
}
}
}