Skip to content

Instantly share code, notes, and snippets.

@zahmedpk
Last active January 6, 2021 13:12
Show Gist options
  • Save zahmedpk/6bc91970d5402c90bf457d7020b0f5f3 to your computer and use it in GitHub Desktop.
Save zahmedpk/6bc91970d5402c90bf457d7020b0f5f3 to your computer and use it in GitHub Desktop.
SwiftUI - Making views appear/disappear with an offset transition
// Xcode 12.3
import SwiftUI
struct ContentView: View {
@State private var arr = [1,2,3]
var body: some View {
ForEach(arr, content: {
number in
RoundedRectangle(cornerRadius: 10)
.foregroundColor(.red)
.overlay(Text("Box #\(number)"))
.transition(.offset(randomOffset()))
})
HStack {
Button("Add a box") {
withAnimation(.easeInOut(duration: 0.8)) {
arr.append( (arr.max() ?? 0) + 1)
}
}
Button("Remove a box"){
withAnimation(.easeInOut(duration: 1)) {
_ = arr.popLast()
}
}
}
}
func randomOffset() -> CGSize {
let radius = Double(max(UIScreen.screenWidth, UIScreen.screenHeight) + 200)
let randomAngle = Double.random(in: 0...359)
let xOffset = radius * cos(randomAngle)
let yOffset = radius * sin(randomAngle)
return CGSize(width: xOffset, height: yOffset)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
extension Int: Identifiable {
public var id: Int {
return self
}
}
extension UIScreen{
static let screenWidth = UIScreen.main.bounds.size.width
static let screenHeight = UIScreen.main.bounds.size.height
static let screenSize = UIScreen.main.bounds.size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment