任意のViewをFlashさせる
code:View+Flashing.swift
import SwiftUI
// definition
struct FlashingModifier: ViewModifier {
let trigger: PassthroughSubject<Void, Never>
@State private var isVisible = false
func body(content: Content) -> some View {
content
.opacity(isVisible ? 1 : 0)
.onReceive(trigger) { _ in
isVisible = true
withAnimation(.easeOut(duration: 0.3)) {
isVisible = false
}
}
}
}
extension View {
func flashing(trigger: PassthroughSubject<Void, Never>) -> some View {
modifier(FlashingModifier(trigger: trigger))
}
}
code:Usage.swift
struct ContentView: View {
let flashTrigger = PassthroughSubject<Void, Never>()
var body: some View {
VStack {
Text("フラッシュするテキスト")
.flashing(trigger: flashTrigger)
Button("フラッシュ開始") {
flashTrigger.send() // イベントを送信するだけ!
}
}
}
}